samedi 21 février 2015

Get notified when annotated objects are created in Java

Intent


I've got a custom Java annotation: @DynamicField



public class RESTEndpointInvoker {
@DynamicField(key="httpTimeout")
private long httpTimeout = 8000L;

public void setHttpTimeout(long t){
this.httpTimeout = t;
}


When someone changes a value in a file or database corresponding to the annotated field, invoke the setter for all instances with that property to reflect the new value. So I need to keep track of all instances that use the annotation, in a map or something, to update them when a change occurs externally:



Map<Key,List<Instance>>


Note: I intend to use some form of WeakHashMap() to avoid holding references to stale instances.


Question


How do I track annotated, but arbitrary, instances if I don't control when and how those instances are created?


Ideally, I want to be notified the moment an instance is created.


Tried


I can scan the classpath for class types, then search each class for annotated fields (see below), but I'm not sure how to track live instances.



//get classes with annotation
Reflections r = new Reflections("com.foo", new TypeAnnotationsScanner());
Set<Class<?>> allAnnotated = r.getTypesAnnotatedWith(DynamicField.class);
//identify fields
for(Class<?> cls : allAnnotated){
for(Field field : cls.getDeclaredFields()){
Class type = field.getType();
String name = field.getName();
if(field.isAnnotationPresent(DynamicField.class)){
....
}
}
}


Solution for Spring beans


If those instances are spring beans, I can do it, but I'd rather avoid that limitation.






Aucun commentaire:

Enregistrer un commentaire