import java.lang.annotation.*;
import java.lang.reflect.*;
public class Annotation {
public static void main(String[] args) {
int tests = 0;
int passed = 0;
Class<?> testClass = AnnotationTest.class;
for (Method m : testClass.getDeclaredMethods()) {
if (m.isAnnotationPresent(Test.class)) {
tests++;
try {
System.out.println(m + " @Test(" + m.getAnnotation(Test.class).value() + "): ");
m.invoke(null);
passed++;
} catch (InvocationTargetException wrappedExc) {
Throwable exc = wrappedExc.getCause();
System.out.println(m + " failed: " + exc);
} catch (Exception exc) {
System.out.println("INVALID @Test: " + m);
}
}
}
System.out.printf("Passed: %d, Failed: %d%n", passed, tests - passed);
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {
String value() default "default";
}
class AnnotationTest {
@Test("chenzq") public static void m1() { } // Test should pass
@Test("jaeson") public static void m2() { // Test Should fail
throw new RuntimeException("Boom");
}
@Test public void m5() { } // INVALID USE: nonstatic method
}
输出为:
public static void com.jaeson.AnnotationTest.m1() @Test(chenzq):
public static void com.jaeson.AnnotationTest.m2() @Test(jaeson):
public static void com.jaeson.AnnotationTest.m2() failed: java.lang.RuntimeException: Boom
public void com.jaeson.AnnotationTest.m5() @Test(default):
INVALID @Test: public void com.jaeson.AnnotationTest.m5()
Passed: 1, Failed: 2