简述:
《Java 编程思想第四版 》 第20章注解使用笔记
1. 用自定义注解,注解方法
CustomizedAnnotation.java
package com.anialy.test.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomizedAnnotation {
int id();
String description() default "no description";
}
TestBean.java
package com.anialy.test.annotation;
public class TestBean {
@CustomizedAnnotation(id = 1, description = "test function !")
public void voidFunc(){};
@CustomizedAnnotation(id = 3)
public String stringFunc(){
return "I'm String";
};
}
CustomizedAnnotationTracker.java 用来表示调用的Bean中哪个id的注解遗漏了(可以看到遗漏了id=2的注解)
package com.anialy.test.annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomizedAnnotationTracker {
public static void trackAnnotation(
List<Integer> annotations, Class<?> clazz){
for(Method m : clazz.getDeclaredMethods()){
CustomizedAnnotation anno =
m.getAnnotation(CustomizedAnnotation.class);
if(anno != null){
System.out.printf("Annotation id: %d, description: %s\n"
, anno.id(), anno.description());
// 集合annotations中的元素(id)如果出现在TestBean中
// 则将该id从 annotations集合中移除
annotations.remove(new Integer(anno.id()));
}
}
for(int i : annotations){
System.out.printf("Missing annotation id: %d\n", i);
}
}
public static void main(String[] args) {
List<Integer> annotations = new ArrayList<Integer>();
Collections.addAll(annotations, 1, 2, 3);
trackAnnotation(annotations, TestBean.class);
}
}
输出: