JDK 1.5 Characteristics Example 5 - Metadata

xiaoxiao2021-03-06  77

Define a metadata. Test.java

Package maoxiang.examples.jdk15.metadata;

Import java.lang.annotation. *;

/ **

* Indeicates what the annotated method is a test method.

* This Annotation SHOULD BE Used Only On Parameterless Static Methods.

* /

@ReTENTION (RETENTIONPOLICY.RUNTIME)

@Target (ElementType.Method)

Public @Iterface test {}

Use metadata in other classes. Foo.java

Package maoxiang.examples.jdk15.metadata;

/ **

* @Author Mao Xiang

*

* /

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 () {}

}

Use metadata. Runtests.java

Package maoxiang.examples.jdk15.metadata;

Import java.lang.reflect.method;

Import maoxiang.examples.jdk15.metadata.demo.test;

/ **

* @Author Mao Xiang

*

* /

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.metata.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, FAILEDs;

}

}

转载请注明原文地址:https://www.9cbs.com/read-108566.html

New Post(0)