2013-07-15 61 views
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.Stringjava.lang.Object作爲一個Class參數,這條線:

return (TypeMirror) entry.getValue(); 

...導致ClassCastException,因爲AnnotationProcessor環境是一種足以實際檢索在這種情況下Class對象。

我已經想出了在Class的情況下如何處理我需要做的所有事情TypeMirror - 我現在需要在我的代碼中處理它們兩個嗎?有沒有辦法從Class對象中獲得TypeMirror?因爲我找不到一個

回答

7

我解決這個問題的解決方案是使用ProcessingEnvironment將結果的Class對象轉換爲TypeMirrors,當我得到類而不是TypeMirrors時。這似乎工作得很好。

AnnotationValue annValue = entry.getValue(); 
if (annValue instanceof TypeMirror) { 
    return (TypeMirror) annValue; 
} 
else { 
    String valString = annValue.getValue().toString(); 
    TypeElement elem = processingEnv.getElementUtils().getTypeElement(valString); 
    return elem.asType(); 
} 
+0

通常說來,註釋處理器API允許通過使用getKind,getTypeKind等來避免instanceof。 – Snicolas

相關問題