How to get type and generic type from javax.lang.model.VariableElement?

619 Views Asked by At

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

There are 1 best solutions below

6
Sagar Gangwal On BEST ANSWER

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.