javax.lang.model Implementation Backed by Core Reflection

Posted 风来了

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javax.lang.model Implementation Backed by Core Reflection相关的知识,希望对你有一定的参考价值。

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;

               //......
            }

 

以上是关于javax.lang.model Implementation Backed by Core Reflection的主要内容,如果未能解决你的问题,请参考以下文章

HTTPS请求处理

Vector源码解析

java分页查询实体类

匿名内部类详解

Servlet随笔

Java多线程-初识并发问题