注解

注解

大多数框架的底层;

注解:给机器看的

注释:给人看的

元注解

Java定义了四个标准的meta-annotation类型,它们被用来提供对其他annotation类型作说明;

@Target

作用域

用于描述注解的使用范围:@Target(value = ElementType.METHOD) 表示只能作用于方法上;value的值不同,作用域不同,类、属性、参数等等很多.

@Retention

使用级别

表示需要在什么级别保存信息 @Retention(value = RetentionPolicy.SOURCE) 表示在源代码上就有作用,总共三种:源代码<类<运行时; SOURCE < CLASS < RUNTIME

@Document

表示将该注解放入javadoc中,没参数的,没啥卵用,直接用就好;

@Inherited

表示子类可以继承父类中的该注解

自定义注解

@MyAnnotation(value = "yuge")
public class TestAnnotation {
    @MyAnnotation2(age = 18)
    private String aaaa;
    @MyAnnotation("yuge")
    public static void main(String[] args) {
    }
}

// Target 表示作用域,此处为类上和方法上
@Target({ElementType.TYPE,ElementType.METHOD})
// Retention 表示注解的级别 此处表示运行时起作用:最高级别
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    // 如果注解里面只有一个参数,那么建议参数名字取value,因为这样,在使用时可以直接@MyAnnotation("yuge")就好,不需要@MyAnnotation(value = "yuge"),偷懒了
    String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
@interface  MyAnnotation2{
    // 参数存在默认值,表示使用注解时,可以不传值
    String value() default "yuge";
    String[] arr() default {"111","222"};
    // 没有默认值的参数,必须传值
    int age();

}
posted @ 2022-01-04 01:10  窃窃私语QAQ  阅读(26)  评论(0编辑  收藏  举报