篡改Junit的@Test注释

本文探讨了如何创建自定义注解,并展示了如何在Java中使用它们来增强代码的可读性和功能性。
注释是关于代码的代码,即关于程序本身的元数据。
package coupdetat;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
    Class expected();
}
package coupdetat;

public class MyTest {
	
	@Test(expected=MyTest.class)
	public void LvDengXing(){
		System.out.println("Keep the bar green to keep the code clean");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
package coupdetat;

import java.lang.reflect.Method;

public class TestAnnotationParser {
    public void parse(Class<?> clazz) throws Exception {
        Method[] methods = clazz.getMethods();
        int pass = 0;
        int fail = 0;


    for (Method method : methods) {
        if (method.isAnnotationPresent(Test.class)) {
            // this is how you access to the attributes
            Test test = method.getAnnotation(Test.class);
            Class expected = test.expected();
            System.out.println(expected.getName());
            try {
                method.invoke(MyTest.class.newInstance(),null);
                method.invoke(expected.newInstance(),null);
                pass++;
            } catch (Exception e) {
                if (Exception.class != expected) {
                    fail++;
                } else {
                    pass++;
                }
            }
        }
    }
    }
}

package coupdetat;
public class Demo {
    public static void main(String [] args) throws Exception {
        TestAnnotationParser parser = new TestAnnotationParser();
        parser.parse(MyTest.class);
        // you can use also Class.forName 
        // to load from file system directly!
    }
}

运行结果:

coupdetat.MyTest
Keep the bar green to keep the code clean
Keep the bar green to keep the code clean

原文:http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值