<Java注解> 模拟JUnit的注解实例=
主要代码:
package com.shengsiyuan.contest; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = {ElementType.METHOD}) @Retention(value = RetentionPolicy.RUNTIME) public @interface Test { }
package com.shengsiyuan.contest; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ApplicationRun { public void run(String className) { try { Class<?> clazz = Class.forName(className); Object obj = clazz.newInstance(); Method[] methods = clazz.getMethods(); for (Method method : methods) { if(method.isAnnotationPresent(Test.class) && method.getGenericParameterTypes().length == 0) { method.invoke(obj, new Object[0]); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
测试:
package com.shengsiyuan.contest; public class MyClass { public void method1() { System.out.println("method1"); } @Test public void method2() { System.out.println("method2"); } @Test public int add(int a, int b) { return a + b; } @Test public void doSomething(String str) { System.out.println(str); } @Test public void doSomething2() { System.out.println("doSomething2()"); } }
package com.shengsiyuan.contest; public class MTest { public static void main(String[] args) { new ApplicationRun().run("com.shengsiyuan.contest.MyClass"); } }
执行结果如下:

浙公网安备 33010602011771号