Java 8对注解处理提供了两点改进:可重复的注解及可用于类型的注解。
写一个注解,如下
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR,
LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE})
public @interface MyAnnotation {
String value() default "编程指南";
}
//其中RetentionPolicy
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
//ElementType如下
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
jdk8以前想实现可重复的注解需要这样
//1. 写一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR,
LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE})
public @interface MyAnnotation {
String value() default "编程指南";
}
//2. 写一个数组类型的注解
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR,
LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE})
public @interface MyAnnotations {
MyAnnotation[] value() default {};
}
//3.使用示例
//重复注解报错 //Duplicate annotation. The declaration of
//'com.initit.java8.annotation.MyAnnotation'
//does not have a valid java.lang.annotation.Repeatable annotation
//@MyAnnotation
@MyAnnotation
//重复注解这样用
@MyAnnotations({
@MyAnnotation("注解1"),
@MyAnnotation("注解2"),
@MyAnnotation("注解3"),
})
public class AnnotationDemo {
}
jdk8提供的可重复注解
- 增加元注解,标注为可以重复的注解@Repeatable(MyAnnotations.class),其中参数是一个数组类型的注解
//1.写一个注解 并增加@Repeatable(MyAnnotations.class)
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR,
LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE})
public @interface MyAnnotation {
String value() default "编程指南";
}
//2.建MyAnnotations.class
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER, CONSTRUCTOR,
LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE})
public @interface MyAnnotations {
MyAnnotation[] value() default {};
}
//3. 使用
@MyAnnotation("注解1"),
@MyAnnotation("注解2"),
@MyAnnotation("注解3"),
public class AnnotationDemo {
//jdk8还增加了 类型注解
private @MyAnnotation String name;
}