• 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);
            }
        }
    
    }
  • 相关阅读:
    Notes for GGX paper
    vsix dll缺失问题
    c# 引用其他工程问题
    Springboot+Maven
    http 带cookie值的Post请求(关联测试)
    http 带cookie值的get请求(关联测试)
    DefaultHttpClient 获取cookie信息
    HttpClient+ ResourceBundle接口配置优化
    Cookie和Session的区别
    moco框架——重定向
  • 原文地址:https://www.cnblogs.com/gongxr/p/16360952.html
Copyright © 2020-2023  润新知