javax.lang.model Implementation Backed by Core Reflection
1.javax.lang.model: How do I get the type of a field?
TypeElement : Represents a class or interface program element. Provides access to information about the type and its members. Note that an enum type is a
kind of class and an annotation type is a kind of interface.
VariableElement: Represents a field, enum
constant, method or constructor parameter, local variable, resource variable, or exception parameter.
In java.lang.reflect
, one would do:
Field someField = ...;
Class<?> fieldType = someField.getType();
But what do I do with javax.lang.model
's VariableElement
(which may or may not represent a field)? A corresponding return value would be (I guess) TypeElement
.
VariableElement someField = ...;
TypeElement fieldType = someField.???;
So, in javax.lang.model
, how do I get the type (or TypeElement
) of a field, represented by VariableElement
?
public class SomeClass {
private final ProcessingEnvironment pe = /* get it somewhere */;
private final Types typeUtils = pe.getTypeUtils();
public TypeElement getExtracted(VariableElement ve) {
TypeMirror typeMirror = ve.asType();
Element element = typeUtils.asElement(typeMirror);
// instanceof implies null-ckeck
return (element instanceof TypeElement)
? (TypeElement)element : null;
}
}
It seems that the class Types
has to be got from current ProcessingEnvironment
because some of its internals depend on it, so it's not a usual utility class.
二。process
for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) { // Check if a class has been annotated with @Factory /** * 我们为什么不这样判断呢if (! (annotatedElement instanceof TypeElement) )? * 这是错误的,因为接口(interface)类型也是TypeElement。 * 所以在注解处理器中,我们要避免使用instanceof,而是配合TypeMirror使用EmentKind或者TypeKind。 */ if (annotatedElement.getKind() != ElementKind.CLASS) { throw new ProcessingException(annotatedElement, "Only classes can be annotated with @%s", Factory.class.getSimpleName()); } // We can cast it, because we know that it of ElementKind.CLASS //因为我们已经知道它是ElementKind.CLASS类型,所以可以直接强制转换 TypeElement typeElement = (TypeElement) annotatedElement; //...... }