Question

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.

Was it helpful?

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.

OTHER TIPS

One way is to invoke the method dynamically using the name of it:

Annotation annotation = getAnnotation();
Class<? extends Annotation> annotationType = annotation.annotationType();
Object result = annotationType.getMethod("method").invoke(annotation);

This approach is quite risky and totally compromise the code refactoring if needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top