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>?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With