** During Annotation Processing, the target class is not loaded in the ClassLoader on the processor side, so you cannot get the Class by this method **
~~ Get Class from # Element ~~
~~-Type Element If (Element of class), Class of that Element ~~ ~~-Variable Element (variables such as fields / enum constants) The variable type Class ~~
Get ~~.
There are about 3 other types of Elements, but I haven't written them because they haven't been verified and there seems to be no need to get Class
~~ I don't care about the mechanism, just move it for the time being! If you are a person, please use this code. Please copy and paste it in a suitable place. ~~
fun Element.getDeclaredClass(): Class<*> = ((asType() as DeclaredType).asElement() as TypeElement).qualifiedName.let { name -> ClassLoader.getSystemClassLoader().loadClass(name.toString())}
Since it is an extension function of ~~ Element, getDeclaredClass () is called and used as it is from the Element fetched from around roundEnv.getElementsAnnotatedWith ()
. ~~
~~ ## Process for getting Class from Element ~~
~~ 1. Call ʻElement # asType ()to get the TypeMirror of the type. 2. Cast the obtained value to DeclaredType. 3. Call
DeclaredType # asElement ()` to get the Element of type.
4. Cast the obtained value to TypeElement
5. Get the binary name (fully qualified name) of the class from TypeElement
6. Get Class from ClassLoader using binary name ~~
~~ After all, you can't convert Element directly to Class. You will get the Class through the ClassLoader. ~~
~~ ʻAbout Element # asType`. JavaDoc is ~~
~~> Returns the type defined by this element. ~~
It says ~~. This returns the type of the variable if it's a Variable Element, or the type that the Element itself represents if it's a Type Element. By the way, the Element acquired in 3 is the same as the first Element, so in the case of Type Element, skipping 1 to 4 and 5 and 6 will be enough. How 1 ~ 4 get the Type Element of type from Variable Element How 5 ~ 6 get Class from Type Element It will be. ~~
~~ Here is the code I actually wrote ~~
fun Element.getDeclaredClass(): Class<*> {
return ((asType() as DeclaredType).asElement() as TypeElement).qualifiedName.let { name ->
ClassLoader.getSystemClassLoader().loadClass(name.toString())
}
}
~~ Would it be like this if written in Java? ~~
public Class<?> getDEclaredClass(Element element) {
String name = ((TypeElement)((DeclaredType)element.asType()).asElement()).getQualifiedName().toString()
return ClassLoader.getSystemClassLoader().loadClass(name)
}
Recommended Posts