diff --git a/javaSE-day12/src/com/inmind/annotation03/JunitDemo10.java b/javaSE-day12/src/com/inmind/annotation03/JunitDemo10.java new file mode 100644 index 0000000..9c40654 --- /dev/null +++ b/javaSE-day12/src/com/inmind/annotation03/JunitDemo10.java @@ -0,0 +1,18 @@ +package com.inmind.annotation03; + +public class JunitDemo10 { + + public void method1(){ + System.out.println("测试方法1执行了"); + } + + @MyTest + public void method2(){ + System.out.println("测试方法2执行了"); + } + + @MyTest + public void method3(){ + System.out.println("测试方法3执行了"); + } +} diff --git a/javaSE-day12/src/com/inmind/annotation03/JunitTest10.java b/javaSE-day12/src/com/inmind/annotation03/JunitTest10.java new file mode 100644 index 0000000..2317016 --- /dev/null +++ b/javaSE-day12/src/com/inmind/annotation03/JunitTest10.java @@ -0,0 +1,29 @@ +package com.inmind.annotation03; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/* +junit测试框架简单实现 +注解(自定义注解)+反射(识别注解+解析注解) + +实现步骤: +1.自定义注解 @MyTest +2.反射获取所有的带有该注解的方法让他们执行 + */ +public class JunitTest10 { + public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { + //获取测试类的Class对象 + Class clazz = JunitDemo10.class; + //获取JunitDemo10所有的方法 + Method[] methods = clazz.getMethods(); + System.out.println(methods.length); + //遍历判断每个方法对象上是否有@MyTest注解 + for (Method method : methods) { + boolean flag = method.isAnnotationPresent(MyTest.class); + if (flag) { + method.invoke(clazz.getConstructor().newInstance()); + } + } + } +} diff --git a/javaSE-day12/src/com/inmind/annotation03/MyTest.java b/javaSE-day12/src/com/inmind/annotation03/MyTest.java new file mode 100644 index 0000000..6ee7d1e --- /dev/null +++ b/javaSE-day12/src/com/inmind/annotation03/MyTest.java @@ -0,0 +1,11 @@ +package com.inmind.annotation03; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface MyTest { +}