编程语言

img maoxiang

JDK 1.5 特性使用实例5--metadata

发表于2004/10/10 11:54:00  962人阅读

分类: Web 开发技术

 

定义一个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);

}

 

}

 

阅读全文
0 0

相关文章推荐

img
取 消
img