注解(Annotation)
注解相当于一种标记,在程序中加上注解相当于给程序打上某种标记。注解可以加在包、类、方法、属性、方法的参数和局部变量上。
Annotation是一个接口,定义为:public interface Annotation
,从JDK1.5开始提供。程序可以通过反射来获取指定程序元素的Annotation对象,然后通过Annotation对象来取得注解里的元数据。Annotation不影响程序的执行。
几个常用的Annotation
@Override
用来指定方法的覆写,他强调一个子类必须覆写其父类的方法。如:
class Fruit{
public void info() {
}
}
class Apple extends Fruit{
//使用@Override指定下面的方法必须覆写父类的info()方法
@Override
public void info() {
}
}
@Override可以帮助程序员避免一些低级错误,比如在接口实现类或子类中避免把覆写的方法名称写错,参数类型错误等。
过时标记(@Deprecated)
Deprecated标记某个程序元素(方法、类等)已经过时,当其他程序使用已经过时的类或方法时候编译器就会给出警告(虽然会给出警告,但是还是可以继续使用,只是不推荐使用)。
@Deprecated
class Fruit{
public void info() {
}
}
class Apple extends Fruit{
@Override
public void info() {
}
}
压制警告(@SuppressWarnings)
@SuppressWarnings表示被该Annotation修饰的元素(以及该元素的所有子元素)取消显示指定的编译器警告。
public class Demo {
@SuppressWarnings({"rawtypes", "unchecked" })
public static void main(String[] args) {
@SuppressWarnings("unused")
List<String> list = new ArrayList();
}
}
Java8的函数式接口@FunctionalInterface
@FunctionalInterface用来指定某个接口必须是函数式接口的。(@FunctionalInterface只允许修饰接口,不允许修饰其他元素)
@FunctionalInterface
interface myInterface{
abstract void fun1();
abstract void fun2();
}
以上代码就会出现以下错误:
Invalid ‘@FunctionalInterface’ annotation; myInterface is not a functional interface
因为@FunctionalInterface只是告诉编译器检查这个接口,保证该接口只有一个抽象方法,否则编译器就会报错。
JDK中的元Annotation
使用@Retention
@retention只能用于修饰Annotation定义,用于指定被修饰的Annotation可以保留多长时间,他只包含一个RetentionPolicy类型的value成员变量。value成员变量的值只能是以下三个:
- RetentionPolicy.CLASS:编译器将把Annotation记录在class文件中,当运行Java程序时,JVM不可获取Annotation信息,这是默认值。
- RetentionPolicy.RUNTIME:编译器将把Annotation记录在class问价中,当运行Java程序的时候,JVM可以获取到Annotation信息,程序可以通过反射获取该Annotation信息
- **RetentionPolicy.SOURCE:**Annotation只保留在源代码中,编译器直接丢弃这种Annotation。
如果要想通过反射取得注解信息,就需要使用value值为RetentionPolicy.RUNTIME的@Retention。
使用@Target
@Target也只能修饰一个Annotation,他用于指定被修饰的Annotation能用于哪种程序单元。@Target元Annotation也只包含一个名为value的成员变量。该变量只能是以下的值:
value值 | 能修饰的对象 |
---|---|
ElementType.ANNOTATION_TYPE | 只能修饰Annotation |
ElementType.CONSTRUCTOR | 只能修饰构造器 |
ElementType.FIELD | 只能修饰成员变量 |
ElementType.LOCAL_VARIABLE | 只能修饰局部变量 |
ElementType.METHOD | 只能修饰方法 |
ElementType.PACKAGE | 只能修饰包定义 |
ElementType.PARAMETER | 可以修饰参数 |
ElementType.TYPE | 可以修饰类、接口、或枚举类型 |
@Documented
用于指定被该Annotation修饰的Annotation类将被javadoc工具提取成文档
@Inherited
用于指定被他修饰的Annotation将具有继承性,如果某个类使用了@Inherited修饰,则该类的子类将自动使用@Inherited修饰。
自定义Annotation
定义Annotation
定义新的Annotation类型使用@interface关键字。也可以在定义Annotation的成员变量时为其指定初始值,指定成员变量的初始值可使用default 关键字。
//定义一个新的Annotation
[public] @interface myAnnotation{
}
或
//定义一个新的Annotation
[public] @interface myAnnotation{
//定义带两个成员变量的Annotation
//Annotation成员变量以方法的形式给出
String name() default "jack";
int age() default 15;
}