5

我有 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 注释,因为不允许在注释中继承。或者有可能以某种方式做吗?

感谢您的任何建议或帮助。

4

2 回答 2

6

为什么不使用类型安全的方式来检索您的注释?

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

如果找不到您的注释,则返回 null。

请注意,这也适用于字段和方法。

于 2011-04-29T13:47:01.030 回答
5

一种方法是使用它的名称动态调用该方法:

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

这种方法风险很大,如果需要的话,完全会影响代码重构。

于 2011-04-29T13:22:31.677 回答