Find singletons in a Java application
Find singletons in a Java application
6. August 2014 Keine Kommentare zu Find singletons in a Java applicationThere might be situations where a constraint needs to verify that a certain type is implemented as singleton. In the world of containers (e.g. EJB, CDI) these can be easily identified by the presence of specific annotations:
- javax.inject.Singleton
- javax.ejb.Singleton
- javax.enterprise.context.ApplicationScoped (provides singleton-like semantics)
The situation is a bit more difficult if no container is available and we have to go back to the „classical“ singleton pattern. In Java this usually means an implementation of a class like the following one:
public class Singleton { private static final INSTANCE = new Singleton(); private Singleton() { } public static Singleton getInstance() { return INSTANCE; } }
Our singleton implementation has the following properties:
- It declares a static field with the class itself as type
- All constructors are private
- It declares a static method which reads the static field and returns an instance of the class
It’s easy to translate these conditions into Cypher:
match (singleton:Class)-[:DECLARES]->(constructor:Constructor) with singleton, collect(constructor) as constructors where all(constructor in constructors where constructor.visibility='private') with singleton match (singleton)-[:DECLARES]->(instance:Field)-[:OF_TYPE]->(singleton), (singleton)-[:DECLARES]->(getInstance:Method)-[:RETURNS]->(singleton), (getInstance)-[:READS]->instance where instance.static and getInstance.static set singleton:Singleton return singleton.fqn, instance.name, getInstance.name
The statement is „weak“ enough to be agnostic against eager or lazy initialization thus it can be used as a template for detecting singletons which are present in an application.
Reference:
http://en.wikipedia.org/wiki/Singleton_pattern
Leave a comment