Search code examples
javareflectionproxyannotations

Java - How to get annotations from Proxy class?


I'm not really familiar with proxy class and I have no idea how does this("annotation") became a proxy object. Can I retrieve annotations from Proxy object?

public static void test(Annotation annotation) {
    System.out.println("ValidBoolean annotation len:" + ValidBoolean.class.getAnnotations().length);
    System.out.println(annotation.getClass().getName() + ":" + annotation.getClass().getAnnotations().length);
    if (annotation instanceof ValidBoolean) {
        ValidBoolean validBoolean = (ValidBoolean) annotation;
        System.out.println("[BOOLEAN]" + validBoolean.getClass().getName() + ":" + validBoolean.getClass().getAnnotations().length);
    }
}

the result is:

ValidBoolean annotation len:3
com.sun.proxy.$Proxy28:0
[BOOLEAN]com.sun.proxy.$Proxy28:0

Solution

  • I'm still not really understanding this Proxy mechanism. But I can get Annotation real class by annotation.annotationType() rather than annotation.getClass(), because annotation is just an interface so annotation.getClass() will only produce a Java Proxy object!

    And it seems, Proxy object doesn't inherit Annotations, this is the most important thing i've learned.