mardi 26 mai 2015

How to work with classloader and annotations

I'm trying to get an annotation from a method but I'm having some trouble. What I'm doing is loading a jar file using URLClassLoader, then I'm inspecting the annotations on methods in classes in that jar using reflection and Method.getAnnotation.
The issue I've encountered is that Method.getAnnotation will return always return null, even if the annotation is there (which we can see using Method.getAnnotations). I've tested the same procedure on the same annotation type on classes which are not loaded with the URLClassLoader and it works fine.
More in depth investigation shows that the canonical name of both instance.annotationType() and MyAnnotation.class are identical. However instance.annotationType().equals(MyAnnotation.class) returns false. The instance itself however is a proxy (com.sun.proxy).

Is there a way to get at the annotation and the fields of the annotation without a considerable amount of reflection?

instance.annotationType().getMethod("value").invoke(instance)

The above would work to get at the field, and iterating through the result of Method.getAnnotations with string comparisons on canonical names would get me the annotation but surely there is a better way?

Also for educational value, what causes this? My guess is that it's because the class of the annotation loaded by the system class loader is somehow different than the class of the annotation loaded by the URL class loader.





Aucun commentaire:

Enregistrer un commentaire