今日总结

2020年10月1日:

注解

1、注解是一种引用数据类型

2、注解的语法:

/* [修饰符列表] @interface 注解类型名{} */
public @interface MyAnnotation{
    
} 

3、注解的使用

一:注解使用时的语法格式@注解类型名

二:注解可以出现在 类、属性、方法、变量、注解类型上等等。

元注解

1、元注解:用来标注“注解类型”的“注解”,称为元注解。

  • Target:这个元注解用来标注"被标注的注解"可以出现在哪些位置上

  • Retention:用来标注“被标注的注解”最终保存在哪里

反射注解

如果获取类上注解的属性值,必须先获取类,然后通过类获取类上的注解,最后获取注解属性值。

如果获取在方法上的注解属性值,必须先获取类,然后获取类的方法,通过方法获取方法上的注解,最后获取注解的属性值。

//只允许该注解标注类、方法
@Target({ElementType.TYPE,ElementType.METHOD})
//希望这个注解可以被反射
@Retention(RetentionPolicy.RNUTIME)
public @interface MyAnnotation{
    String value() default "zhang";
}

//注解测试类
@MyAnnotation("gao")
public class MyAnnotationTest{
    int i;
    public MyAnnotationTest(){
        
    }
    @MyAnnotation
    public void doSome(){
        int i ;
    }
}

//反射注解测试类
public class Reflect AnnotationTest{
    public static void main(String[] args) throws Exception{
        //获取这个类
        Class c = Class.forName("com.reflect.www.MyAnnotationTest");
        //判断是否有@MyAnnotation这个注解,并获取注解对象和属性值
        if(c.isAnnotationPresent(MyAnnotation.class)){//如果有该注解对象则返回true
            //获取注解对象
            MyAnnotation myAnnotation = (MyAnnotation)c.getAnnotation(MyAnnotation.class); //@com.reflect.www.MyAnnotationTest
            //获取注解对象的属性
            String value = myAnnotation.value();
            System.out.println(value);//返回最后一次修改的value值
       
   
        }
    }
}
原文地址:https://www.cnblogs.com/yitiaokuailedexiaojingyu/p/14104840.html