3

I'm using annotation processing and javapoet library to generate some source code.

Say, I've a

VariableElement fieldElement

and if

System.out.println("type:- " + fieldElement.asType().toString());

prints

type:- java.util.Set<com.example.demo.test.model.User>

How do I get the Set class and User class so I can do something like this with javapoet?

ClassName user = ClassName.get("com.example.demo.test.model", "User");
ClassName set = ClassName.get("java.util", "Set");
TypeName setOfUsers = ParameterizedTypeName.get(set, user);

Some string comparison would get the job done, but doesn't seem like the ideal approach.

1 Answer 1

2

You can try below code.

For getting that User class you can use fieldElement.getEnclosingElement(), it will give you class name with full package name.

Now if you want only name of that class you can use enclosingElement.getSimpleName().

And to get enclosedByElement you can use TypeSymbol.Simply cast fieldElement.asType() to Type and get tsym attribute.

        VariableElement fieldElement;

        Symbol.TypeSymbol containerForEnclosingElement=((Type)fieldElement.asType()).tsym;
        Element enclosingElement=fieldElement.getEnclosingElement();

        System.out.println("containerForEnclosingElement:- " +  containerForEnclosingElement);
        System.out.println("enclosingElement:- " +  enclosingElement);
        System.out.println("enclosingElement Name:- " +  enclosingElement.getSimpleName());
        System.out.println("fieldElement without root Type:- "+((Type) fieldElement.asType()).getTypeArguments().get(0));

Above code will print output as below.

containerForEnclosingElement:- java.util.Set
enclosingElement:- com.example.demo.test.model.User.
enclosingElement Name:- User
fieldElement without root Type:- com.example.demo.test.model.User

You can also create one Utility method to get this two values.

This will help you.

Sign up to request clarification or add additional context in comments.

6 Comments

fieldElement.getEnclosingElement() is not giving User. I've Set<User> users as a private variable in another class. It is giving me the another class. Also, from what package does Symbol.TypeSymbol come from?
import com.sun.tools.javac.code.Symbol; You can import this.
If you see my next line fieldElement.getEnclosingElement().getSimpleName(), you will get idea.
as I said fieldElement.getEnclosingElement().getSimpleName() is also returning the name of the class in which Set<User> users is a private field. And getting cannot resolve symbol .tsym after importing com.sun.tools.javac.code.Symbol;
I've teamviewer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.