Search code examples
javacastingannotationsdynamic-typing

Java annotation dynamic typecast


I have 2 java annotation types, let's say XA and YA. Both have some method(). I parse the source code and retrieve Annotation object. Now I'd like to dynamicaly cast the annotation to the real type of it to be able to call the method(). How can I do it without the instanceof statement? I really want to avoid switch-like source. I need something like this:

Annotation annotation = getAnnotation(); // I recieve the Annotation object here
String annotationType = annotation.annotationType().getName();

?_? myAnnotation = (Class.forName(annotationType)) annotation;
annotation.method(); // this is what I need, get the method() called

?_? means I have no idea what would be myAnnotation type. I cannot use the base class for my XA and YA annotations since the inheritance in annotations is not allowed. Or is it possible to do somehow?

Thanks for any suggestion or help.


Solution

  • Why don't you use the typesafe way to retrieve your annotation ?

    final YourAnnotationType annotation = classType.getAnnotation(YourAnnotationType.class);
    annotation.yourMethod();
    

    If your annotation can't be found, null is returned.

    Please note that this also works with fields and methods.