Search code examples
javajavassist

How to inspect runtime annotations with javassist


When attempting to inspect code at runtime using Javassist I need to look at the annotations. As a simple example:

ClassPool pool = ClassPool.getDefault();
CtClass clazz = pool.getCtClass("org.junit.Test");
boolean found = false;
for (Object annotation : clazz.getAvailableAnnotations()) {
    if ("java.lang.annotation.Target".equals(annotation.getClass().getName())) {
        found = true;
    }
}

The problem is this code never sets found = true. The annotation classes that get returned are:

com.sun.proxy.$Proxy8
com.sun.proxy.$Proxy9

Any idea how to get the actual annotations rather then the proxies? Or how one would get the actual annotation from the proxy?


Solution

  • Annotation objects are not direct instances of the annotation type, but instances of some (proxy in this case) object that implements the annotation interface.

    Try if (annotation instanceof java.lang.annotation.Target)