如何编写自定义注解

上一篇java注解初探介绍了注解的基本概念, @Retention注解参数为CLASS时是编译时注解而RUNTIME时是运行时注解,这些在上一篇都有介绍,本篇文章将通过Demo来说说编译时注解和运行时注解。

1、 运行时注解

运行时注解是通过反射在程序运行时获取注解信息,然后利用信息进行其他处理。下面是运行时注解的一个简单Damo,包含Company、EmployeeName、EmployeeSex注解定义以及EmployeeInfoUtil注解处理器,客户端包含EmployeeInfo类(成员变量使用注解)和一个main方法。

Compay代码:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Company {
    public int id() default -1;
    public String name() default "";
    public String address() default "";
}

EmployeeName代码:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EmployeeName {
    String value () default "";
}

EmployeeSex代码:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EmployeeSex {
    enum Sex{Man,Woman}//定义性别枚举
    Sex employeeSex()  default Sex.Man;
}

上一篇文章我们也介绍了,注解的关键是注解处理器,下面的注解处理器仅仅获取注解信息

public class EmployeeInfoUtil {
    public static Map getEmployeeInfo(Class<?> clazz){
        HashMap<String ,String> info = new HashMap<>();
        Field[] fields = clazz.getDeclaredFields();//获取类成员变量
        for (Field field: fields) {//遍历
            if (field.isAnnotationPresent(EmployeeName.class)){//判断是不是EmployeeName类型注解
                EmployeeName employeeName = field.getAnnotation(EmployeeName.class);
                info.put("employeeName",employeeName.value());//获取注解的值
            }
            if (field.isAnnotationPresent(EmployeeSex.class)) {
                EmployeeSex employeeSex = field.getAnnotation(EmployeeSex.class);
                info.put("employeeSex",employeeSex.employeeSex().toString());
            }
            if (field.isAnnotationPresent(Company.class)) {
                Company company = field.getAnnotation(Company.class);
                info.put("company",company.id()+":"+company.name()+":"+company.address());
            }
        }
        return info;
    }
}

EmployeeInfo代码:

public class EmployeeInfo {
    @EmployeeName("zfq")
    private String employeeName;
    @EmployeeSex(employeeSex = EmployeeSex.Sex.Woman)
    private String employeeSex;
    @Company(id = 1,name = "HYR集团",address = "河南开封")
    private String company;
//省略set和get方法
}

客户端代码:

public class EmployeeRun {
    public static void main(String[] args) {
        Map fruitInfo = EmployeeInfoUtil.getEmployeeInfo(EmployeeInfo.class);
        System.out.println(fruitInfo);
    }
}

运行结果:

{employeeName=zfq, employeeSex=Woman, company=1:HYR集团:河南开封}

2、编译时注解

编译时注解是在程序编译的时候动态的生成一些类或者文件,所以编译时注解不会影响程序运行时的性能,而运行时注解则依赖于反射,反射肯定会影响程序运行时的性能,所以一些知名的三方库一般都是使用编译时时注解,比如大名鼎鼎的ButterKnife、Dagger、Afinal等。下面编译时注解是编译时打印使用指定注解的方法的方法信息,注解的定义和运行时注解一样,主要是注解处理器对注解的处理不同 。首先AS的工程中新加Module,选择java Library(指定library name)。

@InjectPrint注解代码:

@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.CLASS)
public @interface InjectPrint {
    String value();
}

InjectPrintProcessor处理器代码:

@SupportedAnnotationTypes("com.example.InjectPrint")//参数是指定注解类型的全路径
public class InjectPrintProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        //获取InjectPrint类型注解,然后遍历
        for(Element element : roundEnvironment.getElementsAnnotatedWith(InjectPrint.class)){
            //元素类型是一个方法
            if(element.getKind() == ElementKind.METHOD){
                //强转成方法对应的element,同
                // 理,如果你的注解是一个类,那你可以强转成TypeElement
                ExecutableElement executableElement = (ExecutableElement)element;
                //打印方法名
                System.out.println(executableElement.getSimpleName());
                //打印方法的返回类型
                System.out.println(executableElement.getReturnType().toString());
                //获取方法所有的参数
                List<? extends VariableElement> params = executableElement.getParameters();
                for(VariableElement variableElement : params){//遍历并打印参数名
                    System.out.println(variableElement.getSimpleName());
                }
                //打印注解的值
                System.out.println("AnnotationValue:"+executableElement.getAnnotation(InjectPrint.class).value());
            }
        }
        return false;
    }
    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }
}

为了我们的AbstractProcessor内被使用,需要在META-INF中显示标识,在resources资源文件夹下新建 META-INF/services/javax.annotation.processing.Processor,其内容:

 com.example.InjectPrintProcessor //注解处理器的全路径

具体的目录结构如下图所示:

image

到此我们就可以build整个工程(要把我们的myanno模块添加到主工程下一起编译,build->Edit Libraries and Dependencies->主工程module->Dependencies->+->Module dependency)生成jar包了,如下图

image

我们可以把myanno.jar拷贝出来,添加到主工程的libs文件夹里,别忘Add As Library
然后,我们就可以在我们的主工程里使用@InjectPrint注解了

image

Build我们的项目,然后Gradle Console控制台就可以看到输出信息了

image

注意:如果你编译过一次下次可能在build的时候可能就看不到控制台输出,这时候你要选择Rebuild Project

自定义运行时和编译时注解到这里就介绍完了,如果感兴趣的同学可以自己写写感受一下,下一篇博客我会去研究一下ButterKnife源码,继续学习。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,860评论 25 709
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,985评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,079评论 19 139
  • 想要做成某件事情的话,工具是非常重要的,也就是我们经常说的磨刀不误砍柴工, 工具是非常重要的,就像以前我们去一个地...
    A小蚊子阅读 149评论 0 1
  • 姓名:张冰 公司:宁波禾隆新材料有限公司 组别:312期努力一组 【日精进打卡第53天】 【知~学习】 《六项精进...
    木头戏阅读 152评论 0 0