Java注释动态类型转换

Pav*_* S. 5 java annotations casting dynamic-typing

我有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
Run Code Online (Sandbox Code Playgroud)

?_?意味着我不知道什么是myAnnotation类型.我不能将基类用于我的XA和YA注释,因为不允许在注释中继承.或者有可能以某种方式做?

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

fau*_*omi 6

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

final YourAnnotationType annotation = classType.getAnnotation(YourAnnotationType.class);
annotation.yourMethod();
Run Code Online (Sandbox Code Playgroud)

如果找不到注释,则返回null.

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

  • 这并不能解决我的问题.我需要为我使用的每个MyAnnotationType声明这一行.classType.getAnnotation(YourAnnotationType.class); 所以它将再次看起来像开关. (2认同)

Dam*_*ash 5

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

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

这种方法风险很大,如果需要,完全会破坏代码重构.