2011-04-29 92 views
5

我有2个java注释类型,比方说XA和YA。两者都有一些方法()。我解析源代码并检索Annotation对象。现在我想动态地将注释转换为它的实际类型以便能够调用method()。如何在没有instanceof声明的情况下执行此操作?我真的想避免像开关一样的来源。我需要这样的:Java注释动态类型转换

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批注。或者有可能做些什么?

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

回答

6

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

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

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

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

+0

这也适用于方法和领域。 – 2011-04-29 14:08:56

+1

这并不能解决我的问题。我需要为我使用的每个MyAnnotationType声明这一行。 classType.getAnnotation(YourAnnotationType.class);所以它会再次看起来像开关。 – 2011-04-29 18:19:01

5

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

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

这种做法是非常危险的,如果需要完全危及代码重构。

+0

很棒!我从'@ Table'注释中获取name属性的方式是使用一些简单的正则表达式从'annotation.toSring()'中提取表名,但是您的解决方案更加优雅。 – 2016-08-24 12:57:36