dinesh707
dinesh707

Reputation: 12592

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

Upvotes: 11

Views: 4337

Answers (2)

biziclop
biziclop

Reputation: 49754

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.

Upvotes: 13

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

You can find the super class of any Java Object through reflection. explained here http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/class/getSuperclass.html

regarding implementing classes. that's more difficult as I believe a given class never "knows" which classes extend it. You will need to build need an elaborate tree of inheritence to get the full picture.

Upvotes: -3

Related Questions