Fork me on GitHub

自定义注解-入门

自定义注解

一.自定义注解时常用的几个注解

1.@Target:

表明该注解可以申明的位置
例:value = {ElementType.FIELD, ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER}
表明该注解可以生命到字段属性,类,方法,和参数上面

2.@Retention:表明注解加载的时机

例:RetentionPolicy.RUNTIME,表明在运行的时候可以加载,一般情况下都使用这个,
因为反射实现代码的时候是在程序运行时执行的。

3.@Inherited

表明被自定义的注解修饰的类在这个类的子类中也起作用
例:在FatherClass上声明了一个自定义注解,在SonClass上也继承了该注解


二.反射实现自定义注解的属性注入

@TestAnnotation(age = 12)
private Integer id;

@TestAnnotation(name = "lisi")
private String name;

例:要将12注入id中,lisi注入name中

//获得这个类的所有属性
Field[] declaredFields = testDemoClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
    //获得有自定义注解的所有字段  
    TestAnnotation annotation = declaredField.getAnnotation(TestAnnotation.class);
    if(annotation != null){
        //获得自定义注解中的属性值
        String name = annotation.name();
        int age = annotation.age();
        declaredField.setAccessible(true);
        //获得属性的类型
        Type genericType = declaredField.getGenericType();
        String type = genericType.toString();
        if (type.equals("class java.lang.Integer")){
            //给属性设置值
            declaredField.set(testDemo, age);
        }else if (type.equals("class java.lang.String")){
            declaredField.set(testDemo, name);
        }else {
            return;
        }
    }
}

三.自定义注解在方法上实现方法的形参注入

try {
    Class<TestDemo> testDemoClass = TestDemo.class;
    Method[] declaredMethods = testDemoClass.getDeclaredMethods();
    for (Method declaredMethod : declaredMethods) {
        TestAnnotation annotation = declaredMethod.getAnnotation(TestAnnotation.class);
        if (annotation != null){
            int parameterCount = declaredMethod.getParameterCount();
            if (parameterCount == 2){
                declaredMethod.invoke(testDemoClass.newInstance(),1, "2");
            }else {
                declaredMethod.invoke(testDemoClass.newInstance(), null);
            }
        }
    }
} catch (Exception e) {
e.printStackTrace();
}

PS:以上只是自定义注解中简单的使用,更深入的在自定义注解中定义Class,接下来在项目中深入了再更新