Dynamic type

I have two java annotations, say XA and YA. Both have some method (). I parse the source code and retrieve the Annotation object. Now I would like to dynamically apply the annotation to the real type so that I can call the () method. How can I do this without instructions instanceof? I really want to avoid a source like a switch. 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 don’t know what myAnnotation type will be. I cannot use the base class for my XA and YA annotations, since inheritance of annotations is not allowed. Or can I do it somehow?

Thanks for any suggestion or help.

+5
source share
2

?

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

, null.

, .

+6

- , :

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

, .

+5

All Articles