定义一个metadata . Test.java
package maoxiang.examples.jdk15.metadata;
import java.lang.annotation.*;
/**
* Indicates that the annotated method is a test method.
* This annotation should be used only on parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
在别的类中使用metadata. Foo.java
package maoxiang.examples.jdk15.metadata;
/**
* @author 毛翔
*
*/
public class Foo {
public static void main(String[] args) {
}
@Test public static void m1() { }
public static void m2() { }
@Test public static void m3() {
throw new RuntimeException("Boom");
}
public static void m4() { }
@Test public static void m5() { }
public static void m6() { }
@Test public static void m7() {
throw new RuntimeException("Crash");
}
public static void m8() { }
}
利用metadata . RunTests.java
package maoxiang.examples.jdk15.metadata;
import java.lang.reflect.Method;
import maoxiang.examples.jdk15.metadata.Demo.Test;
/**
* @author 毛翔
*
*/
public class RunTests {
public static void main(String[] args) throws Exception {
int passed = 0, failed = 0;
for (Method m : Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(maoxiang.examples.jdk15.metadata.Test.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);
}
}
本文地址:http://com.8s8s.com/it/it14820.htm