MyAnnotation.java

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    //--问题1 : 注解中元素可以是哪些类型 
    //-- 注解中的元素以下:int,String,Class,Enum,Annotation,以及以上类型的数组
    //-- 不可以的是接口.
    public int id();
    public String description() default "no description";

}

Test.java

public class Test {
   
    @MyAnnotation(id = 12,description = "这是method方法的描述")
    public void method(){
       
    }
   
    @MyAnnotation(id = 10)
    public void method1(){
       
    }

    @MyAnnotation(id = 20,description = "这是method2方法的描述")
    public void method2(){
       
    }
}

AnnotationInterpreter.java //注解解释器

 

/**
* 注解解释器
* @author edu
*
*/
public class AnnotationInterpreter {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 10,12,20,30);
        interpreter(list,Test.class);
    }
    /**
     * 通过反射库中的API获取注解的元素
     * @param cl
     * @param list
     */
    public static void interpreter(List<Integer> list, Class<Test> cl){
        //--获取指定类型中所有的方法
        for (Method m : cl.getDeclaredMethods()) {
            //--从方法上获取所有的指定类型的注解.
            MyAnnotation ma = m.getAnnotation(MyAnnotation.class);
            if (ma != null) {
                System.out.println("发现注解元素:"+ma.id());
                System.out.println("发现注解元素:"+ma.description());
                //--从集合中移除元素(Integer)
                list.remove(new Integer(ma.id()));
            }
        }
        for (Integer integer : list) {
            System.out.println("没有被使用的元素的值:" + integer);
        }
    }
}