How to find class instance at runtime in Java?

Suppose I have a class with annotation, for example:

@MyConfig
class MyConfiguration {

    @MyParameter
    String parameter;
}

If I know that an instance of this class exists (for example, one was created in another thread), how can I get a reference to the instance elsewhere. I am trying to find an instance using @Annotation.

+4
source share
1 answer

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). , . - , - , .

// somewhere accessible to both the constructing and accessing code, such as a
// public static field on the Annotation
Map<Class<? extends Annotation>,Object> annotationMap = new HashMap();

// wherever the instance is constructed
annotationMap.put(MyConfig.class, new MyConfiguration());

// wherever the instance is needed
MyConfiguration myConf = (MyConfiguration)annotationMap.get(MyConfig.class);

, , Object, , . , , , . , , , , .


, MyConfiguration , , , :

@MyConfig
class MyConfiguration {
  public MyConfiguration() {
    // note this is potentially dangerous, as this isn't finished constructing
    // yet so be very cautious of this pattern, even though it might seem cleaner
    annotationMap.put(MyConfig.class, this);
  }
}

, MyConfiguration, annotationMap .


, , . , , , ; , - , . , , ? , ?

, Singleton - , MyConfiguration, , . :

@MyConfig
class MyConfiguration {
  private static MyConfiguration INSTANCE = null;

  public static MyConfiguration getInstance() {
    // note this is not thread-safe
    // see the above link for several thread-safe modifications
    if(INSTANCE == null) {
      INSTANCE = new MyConfiguration();
    }
    return INSTANCE;
}

MyConfiguration.getInstance() . , , , ( , , ). , . , , , , - , .

+4

All Articles