注释是关于代码的代码,即关于程序本身的元数据。
package coupdetat;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
Class expected();
}
package coupdetat;
public class MyTest {
@Test(expected=MyTest.class)
public void LvDengXing(){
System.out.println("Keep the bar green to keep the code clean");
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
package coupdetat;
import java.lang.reflect.Method;
public class TestAnnotationParser {
public void parse(Class<?> clazz) throws Exception {
Method[] methods = clazz.getMethods();
int pass = 0;
int fail = 0;
for (Method method : methods) {
if (method.isAnnotationPresent(Test.class)) {
// this is how you access to the attributes
Test test = method.getAnnotation(Test.class);
Class expected = test.expected();
System.out.println(expected.getName());
try {
method.invoke(MyTest.class.newInstance(),null);
method.invoke(expected.newInstance(),null);
pass++;
} catch (Exception e) {
if (Exception.class != expected) {
fail++;
} else {
pass++;
}
}
}
}
}
}
package coupdetat;
public class Demo {
public static void main(String [] args) throws Exception {
TestAnnotationParser parser = new TestAnnotationParser();
parser.parse(MyTest.class);
// you can use also Class.forName
// to load from file system directly!
}
}
运行结果:
coupdetat.MyTest
Keep the bar green to keep the code clean
Keep the bar green to keep the code clean
原文:http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/