Java自定义注解及使用

本文通过一个简单的例子展示注解的工作原理.

1.声明注解类型

@Target(value = ElementType.METHOD) //声明该注解的运行目标: 方法
@Retention(value = RetentionPolicy.RUNTIME) //该注解的生命周期: 运行时
public @interface CanRun { // 通过@interface表示注解类型
    String str() default "wow"; // 注解中携带的元数据
}

2.使用自定义注解

public class AnnotationRunner {

    public void method1() {
        System.out.println("method 1");
    }

    @CanRun(str = "foobar") // 方法2添加了自定义注解的标签同时传入str值
    public void method2() {
        System.out.println("method 2");
    }

    public void method3() {
        System.out.println("method 3");
    }

}

3.测试自定义注解

public class AnnotationTest {

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        AnnotationRunner runner = new AnnotationRunner();
        Method[] methods = runner.getClass().getMethods();


        for (Method method : methods){
            CanRun annos = method.getAnnotation(CanRun.class);
            //System.out.println("1");

            if (annos != null){
                method.invoke(runner);
                System.out.println(annos.str());
            }
        }
    }
}

运行结果:

method 2
foobar
posted @ 2016-08-18 19:30  Yusuzhan  阅读(539)  评论(1编辑  收藏  举报
Fork me on GitHub