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.

Drunken Daddy
  • 7,326
  • 14
  • 70
  • 104

1 Answers1

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.

Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38
  • fieldElement.getEnclosingElement() is not giving User. I've `Set users` as a private variable in another class. It is giving me the another class. Also, from what package does `Symbol.TypeSymbol` come from? – Drunken Daddy Aug 16 '20 at 16:47
  • `import com.sun.tools.javac.code.Symbol;` You can import this. – Sagar Gangwal Aug 16 '20 at 16:48
  • If you see my next line `fieldElement.getEnclosingElement().getSimpleName()`, you will get idea. – Sagar Gangwal Aug 16 '20 at 16:49
  • as I said `fieldElement.getEnclosingElement().getSimpleName()` is also returning the name of the class in which `Set users` is a private field. And getting cannot resolve symbol .tsym after importing com.sun.tools.javac.code.Symbol; – Drunken Daddy Aug 16 '20 at 16:54
  • I've teamviewer. – Drunken Daddy Aug 16 '20 at 16:59
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219915/discussion-between-sagar-gangwal-and-drunken-daddy). – Sagar Gangwal Aug 16 '20 at 17:01