1. 程式人生 > >02-模擬Junit4功能

02-模擬Junit4功能

package com.day2;

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 Test {
    
}

 

package
com.day2; public class User { @Test public void getName() { System.out.println("劉詩華測試"); } @Test public void getTel() { System.out.println("15390725037"); } }

 

package com.day2;

import java.lang.reflect.Method;
import
java.util.ArrayList; import java.util.List; public class Junit5 { public static void main(String[] args) throws Exception { Class clazz = Class.forName("com.day2.User"); Object obj = clazz.newInstance(); Method[] list = clazz.getDeclaredMethods(); List
<Method> arr=new ArrayList<>(); for (Method m : list) { boolean b = m.isAnnotationPresent(Test.class); if(b) { arr.add(m); } } for (Method m : arr) { m.invoke(obj); } } }