7

ここで 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

return (TypeMirror) entry.getValue();

...この場合、 AnnotationProcessor 環境は実際にオブジェクトをClassCastException取得するのに十分親切であるため、結果は になります。Class

TypeMirrorが存在しない場合に必要なすべてのことを行う方法を理解しましたClass-今、コードでそれらの両方を処理する必要がありますか? オブジェクトTypeMirrorからを取得する方法はありますか? Class一つも見つからないから

4

1 に答える 1

11

この問題に対して私が行った解決策は、TypeMirrors の代わりにクラスを取得した場合に、ProcessingEnvironment を使用して結果の 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();
}
于 2013-07-23T18:01:05.717 に答える