Get TypeElement and TypeMirror from Class

In Annotation Processing, the class to be processed can be handled only by Element and TypeMirror, and cannot be handled as Class. Therefore, when comparing with a class that is not the processing target (determining whether the target class inherits a specific class, etc.), it is necessary to obtain TypeElement or TypeMirror from Class. If you can get TypeElement, you can get TypeMirror with ʻElement # asType ()`, so if you can get TypeElement from Class, it will be solved.

The method to use is java.lang.model.util.Elements # getTypeElement (CharSequence name) java.lang.model.util.Elements is an interface. You can get an instance with ProcessingEnvironment # getElementUtils (). Therefore, you can get it by referring to processingEnv in the class that inherits AbstractProcessor. So the code looks like this: By the way, Java is Java 8.

ExampleProcessor.java


Elements elementUtils = processingEnv.getElementUtils()
TypeElement element = elementUtils.getTypeElement("java.lang.String")

ExampleProcessor.kt


val elementUtils = processingEnv.elementUtils
val element = elementUtils.getTypeElement("java.lang.String")

The element is now a TypeElement of the java.lang.String class.

Recommended Posts

Get TypeElement and TypeMirror from Class
About go get and go install from Go1.16
Get "2-4, 7, 9" from [4, 7, 9, 2, 3]
[Kotlin] 3 ways to get Class from KClass
Class and model
How to get Class from Element in Java
[Android] Get random keys and values from HashMap
Disassemble and decompile .class files compiled from Kotlin
abstract (abstract class) and interface (interface)
Class and instant part2
Find the address class and address type from the IP address with Java
Implement Java Interface in JRuby class and call it from Java
Get video information from Nikorepo and throw it to Slack
[Kotlin] Get Java Constructor / Method from KFunction and call it
Get attributes and values from an XML file in Java
java.util.Optional class and null and not null
Java class definition and instantiation
Difference between class and instance
Relationship between package and class
How to get and add data from Firebase Firestore in Ruby
[Java] How to convert from String to Path type and get the path
Create a calendar from the Calendar class by specifying the year and month