I'm trying to query the annotations from a class using this code:
for (final Annotation annotation : annotations) System.out.println(annotation);
final JsonSchema[] schemas = clazz.getAnnotationsByType(JsonSchema.class);
if (schemas.length == 0) {
throw new IllegalArgumentException("No JsonSchema annotation found.");
}
If I arrive here via a unit test I get past the schemas.length test. If I do so via a Maven plugin which passes the URL of a class into URLClassLoader().loadClass() then it throws IllegalArgumentException. However, it also prints out:
@mypackage.JsonSchema()
i.e. The annotation appears to be there if I loop through the results of getAnnotations() but isn't found by getAnnotationsByType. What could be causing this?
Edit: If I try looping through and comparing the canonical names then casting to JsonSchema it won't let me as it appears to be a com.sun.proxy which is not an instanceof JsonSchema.
Edit: It's because they're in different class loaders, I'm sure. Quite how to fix that...
Got it.
I was passing an array of URLs for classes to load to new URLClassLoader(). By adding a second parameter of Thread.currentThread().getContextClassLoader() to the constructor it seems to load them into the same ClassLoader and everything then works as expected.