Annotations 2

simple example, IDE为IntelliJ

  • 创建项目
    创建一个标准的带maven的Java项目
    项目的结构如下:
SimpleAnnotationProcessor
--.idea
--src
----main
------java
------resources
----test
--pom.xml
--SimpleAnnotationProcessor.imi

更改Source Folders


Annotations 2_第1张图片
java0.png
  • 创建package和class

package:com.wsl.annotation
class:SimpleAnnotation、SimpleProcessor

目录结构如下


Annotations 2_第2张图片
java1.png
  • 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 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 getSupportedAnnotationTypes() {
        Set annotations = new LinkedHashSet();
        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


    4.0.0

    groupId
    SimpleAnnotationProcessor
    1.0-SNAPSHOT

    
    jar
    
        
            
                maven-compiler-plugin
                2.3.2
                
                    1.6
                    1.6
                    
                    -proc:none
                
            
        
    

执行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,具体原因需要进一步研究

你可能感兴趣的:(Annotations 2)