5
我剛剛進入了javax AnnotationProcessing,並遇到了一個醜陋的情況。我要說明它在一系列的描述我的學習過程中的僞代碼行:優雅地處理TypeMirror和Class
MyAnnotation ann = elementIfound.getAnnotation(MyAnnotation.class);
// Class<?> clazz = ann.getCustomClass(); // Can throw MirroredTypeException!
// Classes within the compilation unit don't exist in this form at compile time!
// Search web and find this alternative...
// Inspect all AnnotationMirrors
for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
if (mirror.getAnnotationType().toString().equals(annotationType.getName())) {
// Inspect all methods on the Annotation class
for (Entry<? extends ExecutableElement,? extends AnnotationValue> entry : mirror.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().toString().equals(paramName)) {
return (TypeMirror) entry.getValue();
}
}
return null;
}
}
return null;
的問題是,現在我找到了,如果客戶端代碼中包含一個核心類像java.lang.String
或java.lang.Object
作爲一個Class
參數,這條線:
return (TypeMirror) entry.getValue();
...導致ClassCastException
,因爲AnnotationProcessor環境是一種足以實際檢索在這種情況下Class
對象。
我已經想出了在Class
的情況下如何處理我需要做的所有事情TypeMirror
- 我現在需要在我的代碼中處理它們兩個嗎?有沒有辦法從Class
對象中獲得TypeMirror
?因爲我找不到一個
通常說來,註釋處理器API允許通過使用getKind,getTypeKind等來避免instanceof。 – Snicolas