根据服务类全路径,方法名,参数全路径,参数json串调用服务类的方法

import com.musi.common.utils.JsonUtils;
import com.musi.common.utils.StringUtils;

import java.lang.reflect.Method;

/**
 * @Author:musi
 * @Date:2019/3/25
 * @Description:
 */
public class ReflectCode {
    public static void reflect(String serviceClassStr,String serviceMethodStr, String param, String requestClassStr) throws Exception {
        if(StringUtils.isNotEmpty(serviceClassStr)&&StringUtils.isNotEmpty(serviceMethodStr)){
            Class serviceClass = Class.forName(serviceClassStr);
            Object service = serviceClass.newInstance();
            Method method = null;
            if(StringUtils.isNotEmpty(requestClassStr)){
                Class requestClass = Class.forName(requestClassStr);
                method = serviceClass.getMethod(serviceMethodStr,requestClass);
                Object request = requestClass.newInstance();

                if(StringUtils.isNotEmpty(param)){
                    request = JsonUtils.parseObject(param,requestClass);
                }
                Object response = method.invoke(service,request);
            }else{
                method = serviceClass.getMethod(serviceMethodStr);
                Object response = method.invoke(serviceClass);
            }
        }else{
            throw new RuntimeException("请求的service类或者方法名为空");
        }
    }
    public static void main(String[] args) throws Exception {
        reflect("com.musi.common.test.reflect.TestService","test","{'param':'1111111'}","com.musi.common.test.reflect.RequestParam");
    }
}

猜你喜欢

转载自blog.csdn.net/musi_m/article/details/88804326