-
1.jdk5.0新增功能
-
2.Annotation其实就是代码里的特殊标记,这些标记可以在编译、类加载,运行时被读取,并且可以在不改变 原有逻辑情况下,在源文件嵌入一些补充信息
@Override:在编译时校验是否重写方法 @Deprecated:用于表示所修饰的元素已过时,通常是因为所修饰结构危险或有更好的方式 @SuppressWarnings:抑制编译器警告
自定义注解-
继承了Annotation接口
-
成员变量以无参数方法声明,类型为八大基本数据类型,Class类型,enum类型,Annotation类型以上所有类型数组
-
参照@SuppressWarning定义
-
注解声明为@interface
-
内部定义成员,通常使用value表示
-
可以指定成员默认值,使用default定义
-
如果定义注解没有成员,表面是一个标识作用
-
如果有成员,必须赋值
-
自定义注解必须配上注解的信息处理流程(反射)才有意义
@interface myAnnotation{ String value()default "hello"; }
-
Retention,指定所修饰注解的生命周期(SOURCECLASS(默认行为))RUNTIME
只有声明为RUNTIME生命周期的注解才能通过反射获取
-
Target,指定修饰注解可以修饰结构的类型
-
documented:表示所修饰注解在被Javadoc解析时,保留下来
-
Inherited:被他修饰的注解将有继承性
public static void main(String[] args) {
//反射获取注解验证子类是否继承了父类注解
Class studentClass = Student.class;
Annotation[] annotations=studentClass.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println(annotations[i]);//@myAnnotation(value=hello)
}
}
可重复注解
-
之前的写法,用数组
-
现在的写法 @Repeatable(myAnnotations.class) myAnnotation的Target和Retention和Inherited要和myAnnotations相同
@Inherited
@Repeatable(myAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@interface myAnnotation{
String value()default "hello";
}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface myAnnotations{
myAnnotation[]value();
}
//@myAnnotations({@myAnnotation(value="world"),@myAnnotation(value="eee")})
//@myAnnotation(value="world")
//@myAnnotation(value="eee")
类型注解
ElementType.TYPE_PARAMETER表示注解能写在类型变量的声明语句中 ElementType.TYPE_USE表示注解能写在任何类型的任何语句中,如异常



