前言:
jdk5开始,java提供了注解的支持
Annotation:是代码里的特殊标记,这些标记可以在编译/类加载/运行时被读取,并执行相应的处理
而基本的注释程序只在编译的时处理
Annotation可以修饰什么?
可以修饰包/类/构造器/方法/成员变量/参数/局部变量,信息存储在name=value中
Annotation到底是什么?
是一个接口,
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
java中的5个基本的Annotation?
@Override
@Deprecated
@Suppress Warnings
@Safa Varargs //java7
@FunctionalInterface //java8
这些都是以类的形式存在的,且都是接口
对应源码了解下?
@Override限定重写父类方法
@Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Override { }
会让编译器检查这个方法,保证父类要包含一个被该方法重写的方法,@ovveride只能修饰方法
@Deprecated:标示已过时
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE}) public @interface Deprecated { } 其他程序使用已过时的类,方法,接口时,编译器会发出警告
@Suppress Warnings:抑制编译器警告
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings {
String[] value(); }
表示取消显示指定的编译器警告@SuppressWarnings(value="unchecked")
@Safa Varargs //java7 抑制堆污染警告
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.CONSTRUCTOR, ElementType.METHOD}) public @interface SafeVarargs {}
用来抑制堆污染警告,使其取消显示的警告
@FunctionalInterface //java8 用来指定某个接口必须是函数式接口
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FunctionalInterface {}
函数式接口:Java8规定,如果一个接口中只有一个抽象方法(可以包含多个默认方法或多个static方法),该接口就是函数式接口
@FunctionalInterface只能修饰接口,告诉编译器检查这个接口,保证该接口只有一个抽象方法,否则就会编译出错