编写注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME) //运行时保留注解
@Target(ElementType.METHOD) //只在方法声明中合法
public @interface Test2 {}
编写使用注解的类,其中m3,m7抛出异常,m1,m5不抛出异常,但m5为实例方法,不存在注解的有效使用:
public class Sample {@Test2public static void m1(){};public static void m2(){};
@Test2 public static void m3(){throw new RuntimeException("Boom");};public static void m4(){};@Test2public void m5(){};public static void m6(){};@Test2public static void m7(){throw new RuntimeException("crash");};public static void m8(){};
}
编写测试类,利用反射运行注解类中所有还有test2注解的方法:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class RunTest {public static void main(String[] args) throws Exception {int tests=0;int passed=0;Class testClass=Class.forName(Sample.class.getName());for(Method m:testClass.getDeclaredMethods()){if(m.isAnnotationPresent(Test2.class)){tests++;try{m.invoke(null);passed++;}catch(InvocationTargetException e){Throwable exc=e.getCause();System.out.println(m+"failed"+exc);}catch (Exception e) {System.out.println("INVALID @TEST2 :" +m);}}}System.out.println("tests:"+tests);System.out.println("passed:"+passed);}
}
运行后的结果为:
public static void springMVC.Sample.m3()failedjava.lang.RuntimeException: Boom
INVALID @TEST2 :public void springMVC.Sample.m5()
public static void springMVC.Sample.m7()failedjava.lang.RuntimeException: crash
tests:4
passed:1