简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM