自定义注解:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Mark {
    String author() default "zhang";
    String comments();
}

使用 @interface 定义注解,Target 是注解使用的目标,Retention 是注解的生存期。

使用注解:

class MarkExample {
    @Mark(author = "zhang", comments = "test")
    private void sayHello() {
        System.out.println("hello");
    }
}

解析注解:

public static void main(String[] args) {
    MarkExample example = new MarkExample();
    // Method[] methods = example.getClass().getMethods();
    // 获得 MarkExample 类声明的方法
    Method[] methods = example.getClass().getDeclaredMethods();
    for (Method m : methods) {
        if (m.isAnnotationPresent(Mark.class)) {
            try {
                // 遍历方法上的注解
                for (Annotation annot : m.getDeclaredAnnotations()) {
                    System.out.println(annot);
                }
                // 获取 Mark 注解,得到属性值
                Mark mark = m.getAnnotation(Mark.class);
                System.out.println(mark.author());
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
    }
}

 

posted on 2018-05-17 10:20  偶尔发呆  阅读(139)  评论(0)    收藏  举报