- java提供了Annotation功能,用于类、构造方法、成员变量、方法、参数的声明中
- 定义Annotation
public @interface NoAnnotationDemo {
}
public @interface OneAnnotationDemo {
String value();
}
public @interface MoreAnnotationDemo {
String describe() default "默认值";
Class type() default void.class;
}
1.@Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.CLASS)
@Retention(RetentionPolicy.RUNTIME)
首 先要明确生命周期长度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方后者一定也能作用。一般如果需要在运行时去动态获取注解信息,那只能用 RUNTIME 注解;如果要在编译时进行一些预处理操作,比如生成一些辅助代码(如 ButterKnife),就用 CLASS注解;如果只是做一些检查性的操作,比如 @Override 和 @SuppressWarnings,则可选用 SOURCE 注解。
2.@Target:定义注解的作用目标
源码为:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface Target {
ElementType[] value();
}
@Target(ElementType.TYPE)
@Target(ElementType.FIELD)
@Target(ElementType.METHOD)
@Target(ElementType.PARAMETER)
@Target(ElementType.CONSTRUCTOR)
@Target(ElementType.LOCAL_VARIABLE)
@Target(ElementType.ANNOTATION_TYPE)
@Target(ElementType.PACKAGE)
3.@Document:说明该注解将被包含在javadoc中
4.@Inherited:说明子类可以继承父类中的该注解
@Target({ElementType.FIELD, ElementType.PARAMETER , ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MoreAnnotationDemo {
String describe() default "默认值";
Class type() default void.class;
}
public class Record {
@MoreAnnotationDemo(describe = "编号", type = Integer.class)
private int id;
@MoreAnnotationDemo(describe = "姓名", type = String.class)
private String name;
@MoreAnnotationDemo(describe = "获取姓名", type = String.class)
public String getName(){
return this.name;
}
@MoreAnnotationDemo(describe = "获取id", type = Integer.class)
public int getSumId(@MoreAnnotationDemo(describe = "编号", type = Integer.class) int num) {
return id + num;
}
}
public class RecordDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
Record record = new Record();
Class clazz = record.getClass();
Constructor[] constructors = clazz.getDeclaredConstructors();
Field[] fields = clazz.getDeclaredFields();
for (Constructor constructor: constructors){
if (constructor.isAnnotationPresent(ConstructorAnnotation.class)){
ConstructorAnnotation constructorAnnotation = (ConstructorAnnotation) constructor.getAnnotation(ConstructorAnnotation.class);
System.out.println(constructorAnnotation.describe());
}
}
for (Field field: fields) {
Annotation[] a = field.getAnnotations();
for (int i = 0; i < a.length; i++) {
MoreAnnotationDemo moreAnnotationDemo = (MoreAnnotationDemo) a[i];
System.out.println(moreAnnotationDemo.describe());
System.out.println(moreAnnotationDemo.type());
}
}
}
}
构造器
编号
class java.lang.Integer
姓名
class java.lang.String