我有两个Java注解类型,假设为XA和YA。它们都有一些method()方法。我解析源代码并检索注解对象。现在我想动态地将注解强制转换为其真实类型,以便能够调用method()方法。如何在不使用instanceof
语句的情况下实现呢?我真的想避免类似switch的源代码。我需要像这样的东西:
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
?_?表示我不知道我的注释类型应该是什么。由于注释中不允许继承,因此我不能使用基类来进行XA和YA注释。或者有没有可能以某种方式实现呢?
感谢任何建议或帮助。