Sunday, March 13, 2022

[SOLVED] how to climb up the hierarchy tree of a TypeMirror object?

Issue

I'm using Java's Annotation Processing mechanism to create serializers for some of my classes.
I'd like to check each field of the currently processed class and make sure that it's a subclass of MyBaseSerializableClass.
My problem is that i only know how to find the immediate super class of the field type:

TypeElement fieldType = (TypeElement)element;
TypeMirror superClassType = fieldType.getSuperclass();

How can i find the super class of superClassType and keep going up the inheritance tree until i hit Object ?


Solution

well i don't know if this is the best way but this is the solution i found:

Types typeUtils = processingEnv.getTypeUtils();
while (!typeElement.toString().equals(Object.class.getName())) {
        element = (TypeElement)typeUtils.asElement(element.getSuperclass());
        // do whatever with element
}


Answered By - yurib
Answer Checked By - Terry (WPSolving Volunteer)