以下是我的方法,我尝试在java中使用反射调用方法:
@PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
@RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
public @ResponseBody
void createRequisition(@RequestBody CreateRequisitionRO[] request,
@RequestHeader("validateOnly") boolean validateOnly) {
logger.debug("Starting createRequisition()...");
for (int i = 0; i < request.length; i++) {
CreateRequisitionRO requisitionRequest = request[i];
// FIXME this has to be removed/moved
requisitionRequest.setFundManager(requisitionRequest.getUserId());
// FIXME might have to search using param level as well
SystemDefault sysDefault = dbFuncs.references.systemDefault
.findByCompanyAndDivisionAndPortfolio(
userContext.getCompany(),
userContext.getDivision(),
requisitionRequest.getPortfolio());
requisitionRequest.setCustodianN(sysDefault.getCustodianN());
gateKeeper.route(requisitionRequest);
}
}
我创建Reflection的方式:
public static void main(String[] args) {
Class[] paramString = new Class[1];
paramString[0] = String.class;
//Object parameter
Class[] parames = new Class[1];
parames[0] = CreateRequisitionRO.class;
Class booleanVal ;
booleanVal = Boolean.class;
Class cls;
CreateRequisitionRO[] request = new CreateRequisitionRO[10];
try {
//load the HexgenWebAPI at runtime
cls = Class.forName("com.hexgen.api.facade.HexgenWebAPI");
Object obj = cls.newInstance();
Method method = cls.getDeclaredMethod("createRequisition", parames,booleanVal);
method.invoke(obj, request,true);
}catch(Exception ex){
ex.printStackTrace();
}
}
我得到以下异常:
The method getDeclaredMethod(String, Class...) in the type Class is not applicable for the arguments (String, Class[], Class)
下一行
Method Method = cls。getDeclaredMethod("createRequisition",帕拉梅斯,booleanVal);
我理解异常,但我的方法参数是对象数组。如果我删除数组,我得到NoSuchMethod Exception
如何解决?
你需要传递一个CreateRequisitionRO
数组的类,而不是一个类数组:替换这个
Class[] parames = new Class[1];
parames[0] = CreateRequisitionRO.class;
与这个:Class parames = CreateRequisitionRO[].class;
另外,由于第二个参数是boolean
,而不是Boolean
,所以需要替换
booleanVal = Boolean.class; // The class of the wrapper Boolean
booleanVal = Boolean.TYPE; // The class of the primitive boolean