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");
}
}
根据服务类全路径,方法名,参数全路径,参数json串调用服务类的方法
最新推荐文章于 2022-02-21 15:08:40 发布