Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the actual type instead of the type parameter when java 1.6 annotation processing

Given these two classes

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

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

If I run this code in an annotation processor, I don't get the result I want.

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

env is a ProcessingEnvironment. entityElement is an Element. (MyClass)

fieldType is set to Key<Foo_>.

What do I need to call to get fieldType set to Key<MyClass>?

like image 915
user507515 Avatar asked Jun 24 '26 12:06

user507515


1 Answers

The type of foo is Foo_ just as it is in the code. I think instead of Key<MyClass> you mean Key<Cow> as that is the type argument used there. Using the Types utility, you can get the field's type as seen from the subclass MyClass by using the method 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>
like image 134
kapex Avatar answered Jun 27 '26 02:06

kapex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!