Java注解动态类型转换

5

我有两个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注释。或者有没有可能以某种方式实现呢?

感谢任何建议或帮助。

2个回答

7
为什么不使用类型安全的方式来检索您的注释?
final YourAnnotationType annotation = classType.getAnnotation(YourAnnotationType.class);
annotation.yourMethod();

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

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


2
这并不能解决我的问题。我需要为每个使用的MyAnnotationType声明这一行。classType.getAnnotation(YourAnnotationType.class); 这样它又会像switch一样。 - Pavel S.

6

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

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

这种方法是相当冒险的,如果需要进行代码重构,它完全会妥协。


非常好!我之前从@Table注解中获取名称属性的方式是通过使用一些简单的正则表达式从annotation.toString()中提取表名,但是你的解决方案更加优雅。 - Jose Rui Santos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接