我有2个java注释类型,让我们说XA和YA。两者都有一些方法()。我解析源代码并检索Annotation对象。现在我想动态地将注释转换为它的真实类型,以便能够调用方法()。如果没有instanceof
声明,我怎么能这样做?我真的想避免像开关一样的源。我需要这样的东西:
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
?_?意味着我不知道什么是myAnnotation类型。我不能将基类用于我的XA和YA注释,因为不允许在注释中继承。或者有可能以某种方式做到吗?
感谢您的任何建议或帮助。
答案 0 :(得分:6)
为什么不使用类型安全的方法来检索注释?
final YourAnnotationType annotation = classType.getAnnotation(YourAnnotationType.class);
annotation.yourMethod();
如果找不到注释,则返回null。
请注意,这也适用于字段和方法。
答案 1 :(得分:5)
一种方法是使用它的名称动态调用该方法:
Annotation annotation = getAnnotation();
Class<? extends Annotation> annotationType = annotation.annotationType();
Object result = annotationType.getMethod("method").invoke(annotation);
这种方法风险很大,如果需要,完全会破坏代码重构。