文章目录[隐藏]
修改 pom.xml
添加依赖 sun.tools:
<dependency>
<groupId>com.sun.tools</groupId>
<artifactId>com.sun.tools</artifactId>
<version>1.6</version>
</dependency>
处理资源文件,跳过执行自定义 processor :
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>META-INF/**/*</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>process-META</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target/classes</outputDirectory>
<resources>
<resource> <directory>${basedir}/src/main/resources/</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
... 省略其它插件
</plugins>
</build>
新建一个编译时注解
这个注解就是对外的注解,后续引用该包的源码上带该注解的都会被处理:
package cn.lzxz1234.jsr269.core;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface Api {
}
新建处理类
编译时的执行类,可以在这里对被编译的类进行方法、字段的增删修改,也可以另外添加新类等任意操作:
package cn.lzxz1234.jsr269.core;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.*;
@SupportedAnnotationTypes("cn.lzxz1234.jsr269.core.Api")
public class ApiProcessor extends AbstractProcessor {
private JavacTrees trees;
private TreeMaker treeMaker;
private Names names;
@Override
public SourceVersion getSupportedSourceVersion()
{
return SourceVersion.latest();
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
this.trees = JavacTrees.instance(processingEnv);
Context context = ((JavacProcessingEnvironment)processingEnv).getContext();
this.treeMaker = TreeMaker.instance(context);
this.names = Names.instance(context);
}
/**
* 处理注解
*
* @param annotations
* @param env
* @return
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
// 处理过程就略了
return true;
}
}
示例处理类没做任何处理,具体逻辑还是看业务要求,在这里推荐个工具类吧:JavaPoet
添加配置文件
在 src/main/resources/META-INF/services
目录里新建配置文件 javax.annotation.processing
:
cn.lzxz1234.jsr269.core.ApiProcessor
All Done !
到这就结束了,打包引用就可以了,这算是最精简的起步指南了吧
发表回复