simple example, IDE为IntelliJ
- 创建项目
创建一个标准的带maven的Java项目
项目的结构如下:
SimpleAnnotationProcessor
--.idea
--src
----main
------java
------resources
----test
--pom.xml
--SimpleAnnotationProcessor.imi
更改Source Folders
- 创建package和class
package:com.wsl.annotation
class:SimpleAnnotation、SimpleProcessor
目录结构如下
- SimpleAnnotation
自定义Annotation, 保留规则为SOURCE, 编译期被丢弃
package com.wsl.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.SOURCE)
public @interface SimpleAnnotation {
}
- SimpleProcessor
这里process的逻辑比较简单,仅仅是打印一下目标Element的name
public class SimpleProcessor extends AbstractProcessor {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
Messager messager = processingEnv.getMessager();
for (TypeElement te : annotations) {
for (Element e : env.getElementsAnnotatedWith(te)) {
messager.printMessage(Diagnostic.Kind.NOTE, "Printing: " + e.toString());
}
}
return true;
}
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> annotations = new LinkedHashSet<String>();
annotations.add(SimpleAnnotation.class.getCanonicalName());
return annotations;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}
- javax.annotation.processing.Processor
resources目录下新建META-INF/services,services目录下新建javax.annotation.processing.Processor,Processor指定自定义的processor
com.wsl.annotation.SimpleProcessor
- package JAR
这里用maven打包,修改pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>SimpleAnnotationProcessor</artifactId>
<version>1.0-SNAPSHOT</version>
<!--增加如下代码-->
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<!-- Disable annotation processing for ourselves. -->
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
</project>
执行mvn clean package, 在target目录生成JAR
- 验证
编写验证类Test.java,如下
import com.wsl.annotation.SimpleAnnotation;
@SimpleAnnotation
public class Test {
@SimpleAnnotation
public static void a1(int x) {
}
public static void a2(String[] arr) {
}
}
wushuanglongdeMac-mini:SimpleAnnotationProcessor wushuanglong$ javac -cp ~/tmp/Simple0.jar Test.java
注: Printing: Test
注: Printing: a1(int)
NOTE:Artifact方式打出来的包没有MATA-INF,具体原因需要进一步研究