注解处理器
如果没有处理注解的工具,那么注解也不会有什么大的作用。对于不同的注解有不同的注解处理器。虽然注解处理器的编写千变万化,但是也有其标准。比如:针对运行时注解会采用反射机制处理,针对编译时注解会采用AbstractProcessor来处理。
- 运行时注解处理器
- 首先我们需要定义运行时注解
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface GET{ String value() default ""; }
- 意味着GET注解用于方法
public class AnnotationTest { @GET(value = "http://ip.taobao.com/59.108.54.37") public String getIpMsg(){ return ""; } @GET(value = "http://ip.taobao.com/") public String getIp(){ return ""; } }
- 接下来写一个简单的处理器
public class AnnotationProcessor { public static void main(String[] args){ Method[] methods = AnnotationTest.class.getDeclaredMethods(); for (Method m: methods){ GET swordsman = m.getAnnotation(GET.class); System.out.println(swordsman.value()); } } }
- 首先我们需要定义运行时注解
- 编译时注解处理器
- 定义注解
@Retention(RetentionPolicy.CLASS) @Target(ElementType.FIELD) public @interface BindView { int value() default 1; }
- 编写注解处理器(新建java library)
public class ClassProcessor extends AbstractProcessor{ /** * 相当于每个处理器的主函数main(),在这里写扫描、评估和处理注解的代码,以及生成java * 文件 * @param set * @param roundEnvironment * @return */ @Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { Messager messager = processingEnv.getMessager(); for (Element element: roundEnvironment.getElementsAnnotatedWith(BindView.class)){ if (element.getKind() == ElementKind.FIELD){ messager.printMessage(Diagnostic.Kind.NOTE, "printMessage:"+element.toString()); } } return false; } @Override public synchronized void init(ProcessingEnvironment processingEnvironment) { super.init(processingEnvironment); } /** * 这是必须指定的方法,指定这个注解处理器是注册给哪个注解的 * @return */ @Override public Set<String> getSupportedAnnotationTypes() { return super.getSupportedAnnotationTypes(); } @Override public SourceVersion getSupportedSourceVersion() { return super.getSupportedSourceVersion(); }
- 在Java 7以后,也可以使用红色部分;但为了android兼容性,不建议使用
@SupportedSourceVersion(SourceVersion.RELEASE_8) @SupportedAnnotationTypes("com...bindview") public class ClassProcessor extends AbstractProcessor{ /** * 相当于每个处理器的主函数main(),在这里写扫描、评估和处理注解的代码,以及生成java * 文件 * @param set * @param roundEnvironment * @return */ @Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { return false; } @Override public synchronized void init(ProcessingEnvironment processingEnvironment) { super.init(processingEnvironment); } }
- 注册注解处理器
- 应用注解
- 定义注解
Dana.Lee
To:Dana_Lee1016@126.com