You cannot just call a reference to an object based on its type or annotations, and you also do not want to do this. The main reason for this is garbage collection - the JVM cleans up the memory for you as objects go beyond; if you could dynamically create new links, the garbage collector could not safely clear anything and you would quickly run out of memory.
, , , .
(, , ) - , Map ( Guava ClassToInstanceMap). , . - , - , .
Map<Class<? extends Annotation>,Object> annotationMap = new HashMap();
annotationMap.put(MyConfig.class, new MyConfiguration());
MyConfiguration myConf = (MyConfiguration)annotationMap.get(MyConfig.class);
, , Object, , . , , , . , , , , .
, MyConfiguration , , , :
@MyConfig
class MyConfiguration {
public MyConfiguration() {
annotationMap.put(MyConfig.class, this);
}
}
, MyConfiguration, annotationMap .
, , . , , , ; , - , . , , ? , ?
, Singleton - , MyConfiguration, , . :
@MyConfig
class MyConfiguration {
private static MyConfiguration INSTANCE = null;
public static MyConfiguration getInstance() {
if(INSTANCE == null) {
INSTANCE = new MyConfiguration();
}
return INSTANCE;
}
MyConfiguration.getInstance() . , , , ( , , ). , . , , , , - , .