注解
什么是注解
注解是给编译器看的,注解可以做到在不改变代码逻辑的前提下嵌入补充信息
java内置的注解
- @Deprecated :用来标记过时的元素,在编译阶段遇到这个注解会发出提醒警告,告诉开发者正在调用一个过时的类、过时的方法
- @SuppressWarnings
该注解的属性值:
rewtypes:抑制未使用泛型的警告
resource:抑制未关闭资源的警告
deprecation:抑制使用了已过时资源的警告
all:抑制所有警告 - @FunctionalInterface 函数式接口
什么是函数式接口:如果这个接口抽象方法只有一个(有且仅有一个),称为函数式接口 - 被@FunctionalInterface 标注的接口中,允许有多个默认方法 和 静态方法
自定义注解
public @interface MyAnnotation {
//以下是使用注解的过程
}
元注解
注解的注解
RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视。
RetentionPolicy.CLASS 注解只被保留到编译进行的时候,它并不会被加载到 JVM 中。
RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们。也就是在允许阶段可以被反射注解
@Target(ElementType.METHOD)
@Retention(RentionPolicy.SOURCE)//
public @interface Override{
}
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
//以下是使用注解的过程
}
public class Test {
public static void main(String[] args) {
Class<Test> testClass = Test.class;
MyAnnotation annotation = testClass.getAnnotation(MyAnnotation.class);
System.out.println(annotation);//@Annotation_.MyAnnotation()//@Annotation_.MyAnnotation() 此注解可以被JVM反射访问到
}
}
@Target:设置注解位置
/**
ElementType.ANNOTATION_TYPE 可以给一个注解进行注解
ElementType.CONSTRUCTOR 可以给构造方法进行注解
ElementType.FIELD 可以给属性进行注解
ElementType.LOCAL_VARIABLE 可以给局部变量进行注解
ElementType.METHOD 可以给方法进行注解
ElementType.PACKAGE 可以给一个包进行注解
ElementType.PARAMETER 可以给一个方法内的参数进行注解
ElementType.TYPE 可以给一个类型进行注解,比如类、接口、枚举
/
@Target(value = {ElementType.METHOD,ElementType.FIELD})//限定注解只能在方法存在或者类型上
public @interface MyAnnotationTest {
}
@Inherited
这个注解能够被继承
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotationTest02 {
//这个注解能够被继承
}
@Repeatable
被这个注解标注的可以被重复使用