Java 注解

一、元注解(注解的注解)

  • @Retention 表明注解的存活的时间。取值如下:
RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视。
RetentionPolicy.CLASS 注解只被保留到编译进行的时候,它并不会被加载到 JVM 中。
RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们。
  • @Documented 说明文档。
它的作用是能够将注解中的元素包含到 Javadoc 中去。
  • @Target 指明注解使用的地方。取值如下:
ElementType.ANNOTATION_TYPE 可以给一个注解进行注解
ElementType.CONSTRUCTOR 可以给构造方法进行注解
ElementType.FIELD 可以给属性进行注解
ElementType.LOCAL_VARIABLE 可以给局部变量进行注解
ElementType.METHOD 可以给方法进行注解
ElementType.PACKAGE 可以给一个包进行注解
ElementType.PARAMETER 可以给一个方法内的参数进行注解
ElementType.TYPE 可以给一个类型进行注解,比如类、接口、枚举
  • @Inherited 继承父类注解。
使用 @Inherited 标注的注解去注解一个父类,若这个父类的子类没有使用任何注解,这该子类相当于使用了 @Inherited 标注的那个注解。

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface Test {}

@Test
public class A {}

public class B extends A {}

说明:子类 B 相当于有 @Test 的注解。
  • @Repeatable 可重复使用的注解
@interface Persons {
    Person[]  value();
}


@Repeatable(Persons.class)
@interface Person{
    String role default "";
}


@Person(role="artist")
@Person(role="coder")
@Person(role="PM")
public class SuperMan{
    
}

说明:注解 @Person 使用了 @Repeatable 元注解,所以 @Person 可以使用多次。
其中多次使用时所带的参数存放在 @Persons 中(@Repeatable 中注入了 Persons.class)。

二、Java 中自带的注解

  • @Deprecated 过时的方法、过时的类、过时的成员变量。
  • @Override 继承。
  • @SuppressWarnings 阻止警告。
  • @FunctionalInterface 函数式接口 ,就是一个具有一个方法的普通接口。

三、注解的属性

  • 注解只传递值
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    
    int id(); default -1;
    
    String msg(); default "Hi";

}

说明:注解 @TestAnnotation,有两个属性值:名为 id 的 int 型的属性值;名为 msg 的 String 型的属性值。
其中 id 的默认值为 -1;msg 的默认值为 "Hi"
  • 使用注解时传值
@TestAnnotation(id=3,msg="hello annotation")
public class Test {

}

//使用默认值传值
@TestAnnotation()
public class Test {

}
  • 注解中只有一个值时的使用
public @interface Check {
    String value();
}

//使用
@Check(value="hi")
int a;

//等同于上面的使用
@Check("hi")
int a;
  • 没有值的注解的使用
public @interface Perform {}

//使用
@Perform
public void testMethod(){}

四、注解的提取

  • isAnnotationPresent 判断是否使用了某注解。
//判断 Test 类是否使用了 TestAnnotation 注解
boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);
  • getAnnotation 获取注解对象
//获取在 Test 类上使用的 TestAnnotaion 注解
TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
  • 获取注解对象中的值
//直接使用注解对象 . 属性值
System.out.println("id:"+testAnnotation.id());
System.out.println("msg:"+testAnnotation.msg());

1.利用反射获取类中的方法或成员变量
2.判断方法或成员变量是否使用了某个注解
3.若使用了,则可提取注解中的值注入方法或给成员变量赋值。

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

推荐阅读更多精彩内容