From bd74563b271eadf402f5f6baa50d8f258c6afb4b Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Thu, 2 Apr 2026 14:35:43 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=9B=E9=98=B6day12-=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E7=AE=80=E5=8D=95=E7=9A=84Junit=E6=A1=86=E6=9E=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/inmind/annotation03/JunitDemo10.java | 18 ++++++++++++ .../com/inmind/annotation03/JunitTest10.java | 29 +++++++++++++++++++ .../src/com/inmind/annotation03/MyTest.java | 11 +++++++ 3 files changed, 58 insertions(+) create mode 100644 javaSE-day12/src/com/inmind/annotation03/JunitDemo10.java create mode 100644 javaSE-day12/src/com/inmind/annotation03/JunitTest10.java create mode 100644 javaSE-day12/src/com/inmind/annotation03/MyTest.java 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 { +}