Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the super class name in annotation processing

I run an annotation processor written by my self to generate some new java code based on annotated classes. Following is what i tried to get the super class name of a currently processed class.

TypeMirror superTypeMirror = typeElement.getSuperclass();
final TypeKind superClassName = superTypeMirror.getKind();
log("A==================" + superClassName.getClass());
log("B==================" + superClassName.getDeclaringClass());

typeElement returns me the current class that annotation processor is processing. I want to know which classes this extends and which classes are implemented by this class. The methods i used are not helpful at all.

Thankx

like image 203
dinesh707 Avatar asked Jun 03 '15 09:06

dinesh707


1 Answers

If I understood the question correctly, Types.directSupertypes() is the method you need.

It will return the type of the direct superclass first, followed by the (directly) implemented interfaces, if there are any.

Regardless of whether they represent a superclass or a superinterface, you should be able to cast them to DeclaredType, which has an asElement() method, that can be used to query things as simple and fully qualified name.

So you'll have something like this:

for (TypeMirror supertype : Types.directSupertypes(typeElement)) {
   DeclaredType declared = (DeclaredType)supertype; //you should of course check this is possible first
   Element supertypeElement = declared.asElement();
   System.out.println( "Supertype name: " + superTypeElement.getSimpleName() );
}

The above works if typeElement is a TypeMirror, if it is a TypeElement, you can get the superclass and the superinterfaces directly by simply calling typeElement.getSuperclass() and typeElement.getInterfaces() separately ( instead of Types.directSupertypes()) but the rest of the process is the same.

like image 83
biziclop Avatar answered Oct 05 '22 02:10

biziclop