Skip to content
This repository has been archived by the owner on Jul 13, 2021. It is now read-only.

###记录几个发现 by yangtao### #5

Closed
BruceWind opened this issue Jun 22, 2017 · 2 comments
Closed

###记录几个发现 by yangtao### #5

BruceWind opened this issue Jun 22, 2017 · 2 comments

Comments

@BruceWind
Copy link
Member

###记录几个发现###

1:AbstractProcessor是本开源项目的核心类,在build过程中,会执行该类的重写方法。process()是该类的核心方法,这相当于每个处理器的主函数main()。你在这里写你的扫描、评估和处理注解的代码,以及生成Java文件。输入参数RoundEnviroment,可以让你查询出包含特定注解的被注解元素。

2:之前在检测类元素的时候,判断是这么写的。

if (annotatedElement instanceof TypeElement) 

这么写并不合理,因为所有的元素类型都是Element,所有要避免使用instanceof。配合TypeMirror使用EmentKind或者TypeKind。

if (annotatedElement.getKind() == ElementKind.CLASS)

3:我们在遍历获取类文件里边的元素时,首先获取的是构造函数。

4:以下是获取注解的代码,返回一个集合

 List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();

5:以下是获取注解类型的代码

DeclaredType declaredType = annotationMirrors.get(i).getAnnotationType();

6:以下是获取注解值的代码,返回一个map

Map<? extends ExecutableElement, ? extends AnnotationValue> map = annotationMirrors.get(i).getElementValues();

7:创建一个新的注解

//通过全类名返回一个类,此类用于生成注解
Class clazz = Class.forName(simpleName);
//创建一个新的注解
AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(clazz);
//for循环遍历集合,用户有可能自定义注解,并且会有多个注解值,看来这块需要遍历保存
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : map.entrySet()) {
    //注解key
    String key = entry.getKey().getSimpleName().toString();
    //注解value()返回的是一个集合Collection,通过迭代出下一个的值
    Object value = entry.getValue().getValue();
    //增加注解初始值
    annotationBuilder.addMember(key, "$S", value);
    //打印信息,在此处遇到一个问题,下边的打印方法貌似会覆盖之前的打印数据。
    messager.printMessage(
            Diagnostic.Kind.ERROR,
            String.format("全类名:" + simpleName + "   注解key:" + key + "   注解值:" + value, this),
            element);
}
//new一个新的注解空间
AnnotationSpec annotationSpec = annotationBuilder.build();

8:messager打印的时候遇到一个问题,最后打印的数据貌似会把之前的数据覆盖,导致在for循环的时候,我一直认为数据是不对的,很坑爹。

@BruceWind
Copy link
Member Author

以后这种东西,不要写入README中。

@workertao
Copy link

好的

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants