2013-07-15 5 views
5

여기에있는 javax AnnotationProcessing으로 들어가고 추악한 경우가 있습니다. 나는 나의 학습 과정을 설명하는 의사 코드 라인의 일련의를 설명합니다 :핸들 유형 미러 및 클래스 정상적으로

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 매개 변수이 줄하십시오 ClassCastException에서

return (TypeMirror) entry.getValue(); 

... 결과는 AnnotationProcessor 환경이 친절하게도 실제로이 경우 Class 개체를 검색하기 때문입니다.

TypeMirror이 없으면 Class이 없어야 할 모든 작업을 수행하는 방법을 알아 냈습니다. 지금 내 코드에서이 두 가지를 모두 처리해야합니까? Class 개체에서 TypeMirror을 얻을 수있는 방법이 있습니까? 왜냐하면 내가 하나를 찾을 수 없기 때문에

답변

7

이 문제를 해결하기위한 해결책은 ProcessingEnvironment를 사용하여 TypeMirrors 대신 클래스가있는 경우 결과 Class 객체를 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