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.
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
Typeand gettsymattribute.Above code will print output as below.
You can also create one Utility method to get this two values.
This will help you.