springframework的ReflectionUtils反射工具类功能举例

import com.shein.dms.common.BasicCase;
import com.shein.dms.utils.MathUtils;
import com.shein.dms.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.testng.annotations.Test;
import java.lang.reflect.Method;

/**
 * @author :gongxr
 * @description:测试反射工具类
 */
@Slf4j
public class TestReflectionUtils extends BasicCase {

    /**
     * 指定无参方法反射执行
     * 步骤:找方法、实例化、反射执行
     */
    @Test
    public void testFindMethod() throws Exception {
        Class<TimeUtils> clazz = TimeUtils.class;
        Method method = ReflectionUtils.findMethod(clazz, "getDateTimeNow");
        Assert.notNull(method, "method方法对象不能为null");
        ReflectionUtils.makeAccessible(method);
        log.info("方法名称:{},参数个数:{}", method.getName(), method.getParameterCount());
        TimeUtils instance = TimeUtils.class.newInstance();
        Object o = ReflectionUtils.invokeMethod(method, instance);
        log.info("result:{}", o);
    }

    /**
     * 指定有参方法反射执行
     * 步骤:找方法、实例化、反射执行
     */
    @Test
    public void testFindMethodParams() throws Exception {
        Class<TimeUtils> clazz = TimeUtils.class;
        Method method = ReflectionUtils.findMethod(clazz, "getDateTimePlusDays", int.class);
        Assert.notNull(method, "method方法对象不能为null");
        ReflectionUtils.makeAccessible(method);
        TimeUtils instance = TimeUtils.class.newInstance();
        Object o = ReflectionUtils.invokeMethod(method, instance, 1);
        log.info("方法名称:{},参数个数:{}", method.getName(), method.getParameterCount());
        log.info("result:{}", o);
    }

    /**
     * 反射调用方法,方法遍历
     * 步骤:找方法、实例化、反射执行
     */
    @Test
    public void testFindMethods() throws Exception {
        Class<MathUtils> clazz = MathUtils.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();
        Assert.notEmpty(declaredMethods, "declaredMethods方法对象不能为null");
        for (Method method : declaredMethods) {
            ReflectionUtils.makeAccessible(method);
            MathUtils instance = MathUtils.class.newInstance();
            Object o = ReflectionUtils.invokeMethod(method, instance, 11);
            log.info("方法名称:{},参数个数:{},结果:{}", method.getName(), method.getParameterCount(), o);
        }
    }

}

 

posted @ 2022-06-09 19:53  星瑞  阅读(765)  评论(0编辑  收藏  举报