自定义Java注解Annotation

1、CopyRight.java

package com.ats.annotation;

public @interface CopyRight {
	String value();
}

2、UnitTest.java

package com.ats.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;

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

3、Foo.java

package com.ats.test;

import com.ats.annotation.UnitTest;

public class Foo {
	@UnitTest
	public static void m1() {
	}

	@UnitTest
	public static void m2() {
		throw new RuntimeException("Crash");
	}

	@UnitTest
	public static void m3() {
	}

	public static void m4() {
	}
	
	public static void m5() {
		throw new RuntimeException("Crash");
	}
}

4、RunTests.java

package com.ats.test;

import java.lang.reflect.Method;

import com.ats.annotation.CopyRight;
import com.ats.annotation.UnitTest;

@CopyRight("2012 NEOHOPE")
public class RunTests {
	public static void main(String[] args) throws Exception {
		
		int passed = 0, failed = 0;
		
		for (Method m : Class.forName("com.ats.test.Foo").getMethods()) {
			if (m.isAnnotationPresent(UnitTest.class)) {
				try {
					m.invoke(null);
					passed++;
				} catch (Throwable ex) {
					System.out.printf("Test %s failed: %s %n", m, ex.getCause());
					failed++;
				}
			}
		}
		
		System.out.printf("Passed: %d, Failed %d%n", passed, failed);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*