2011-04-29 62 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