模仿java的@Test

2018-11-25  本文已影响0人  陈柴盐

定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTest {

}

使用自定义注解

    @MyTest
    public void method1(){
        System.out.println("方法1");
    }

    public void method2() {
        System.out.println("方法2");
    }

    @MyTest
    public  void method3() {
        System.out.println("方法3");
    }

解析注解

    public static void main(String[] args) throws Exception {
        
        //获取Class对象
        Class<MyTestTest> testClass = MyTestTest.class;
        //获取MyTestTest类中的所有方法的对象
        Method[] methods = testClass.getMethods();
        for (Method method : methods) {
            //判断该方法是否存在注解@MyTest
            if (method.isAnnotationPresent(MyTest.class)) {
                System.out.println("method = " + method);
                //获取MyTestTest类的构造器并创建对象
                MyTestTest myTestTest=MyTestTest.class.getConstructor().newInstance();
                //调用方法
                method.invoke(myTestTest);
            }
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读