3

これら2つのクラスが与えられた場合

public class MyClass extends MyAbstractClass<Cow> {
  ...
}

public abstract class MyAbstractClass<Foo_ extends AbstractFoo> {
  ...
  Key<Foo_> foo;
  ...
}

このコードを注釈プロセッサで実行すると、必要な結果が得られません。

for (VariableElement fieldElement : ElementFilter.fieldsIn(env.getElementUtils().getAllMembers((TypeElement)entityElement))) {
    String fieldType = fieldElement.asType().toString();
}

env は ProcessingEnvironment です。entityElement は要素です。(私のクラス)

fieldType が に設定されていKey<Foo_>ます。

fieldType を に設定するには、何を呼び出す必要がありKey<MyClass>ますか?

4

1 に答える 1

3

の型はfooコードFoo_のとおりです。Key<MyClass>あなたの代わりに、Key<Cow>それがそこで使用されている型引数であるためだと思います。タイプユーティリティを使用MyClassすると、メソッドgetDeclaredTypeを使用して、サブクラスから見たフィールドのタイプを取得できます。

// these are the types as declared in the source
System.out.println(fieldElement.asType());      // Key<Foo_>
System.out.println(t.getSuperclass());          // MyAbstractClass<Cow>

// extract the type argument of MyAbstractClass
TypeMirror superClassParameter = ((DeclaredType) t.getSuperclass()).getTypeArguments().get(0);
System.out.println(superClassParameter);        // Cow

// use the type argument and the field's type's type element to construct the fields actual type
DeclaredType fieldType = typeUtils.getDeclaredType(
        (TypeElement) typeUtils.asElement(fieldElement.asType()), superClassParameter);

System.out.println(fieldType);                   // Key<Cow>
于 2011-09-01T12:55:30.380 に答える