简体   繁体   中英

Java reflection querying annotations by type

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()

ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM