Annotaton

image-20230630150645829

常见注解

@deprecated :过时

内置注解

  • @Override – 重写

image-20230630160247463

  • @SuppressWarnings(“all”) – 抑制警告

image-20230630160348703

元注解

image-20230630212334557

@Target [*]

  • 描述注解的使用范围(即:被描述的注解可以用在什么地方)

    • value 可为数组
    • ElementType.
      • METHOD:只能在方法上
      • TYPE:可放在类上
//表示注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@MyAnnotation//  -- TYPE
public class Test02 {
@MyAnnotation// -- METHOD
public void test(){
}
}

//定义一个注解
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@interface MyAnnotation{
}

@Retention [*]

  • 表示需要在什么级别保存该注释信息,用于描述注解的生命周期
  • 表示注解在什么地方有效
  • value
    • RetentionPolicy
    • 有效:SOURCE(代码) < CLASS(运行时)< RUNTIME(运行时)
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation{
}

@Document

  • 开启该注解将被包含在JAVAdoc中
  • 表示是否将注解生成在JAVAdoc中

@Inherited

  • 说明子类可以继承父类中的该注解

自定义注解

image-20230630213711193

  • 属性名为value且单属性可省略
  • 注解可以显式赋值 , 如果没有默认值 , 我们就必须给注解赋值
public class Test03 {
//注解可以显式赋值 , 如果没有默认值 , 我们就必须给注解赋值
@MyAnnotation2(name = "C2C",age = 20)
public void test(){
}

@MyAnnotation3("辰")
public void test2(){
}
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数:参数类型 + 参数名 ();
String name() default "";
int age() default 18;
int id() default -1;//默认值-1,不存在
String[] schools() default {"大学","广东"};

}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}