2013-04-05 82 views
2

下调用一个方法是我的方法,我试图在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); 
     } 
    } 

我创造的反思方式:

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”,parames,booleanVal);

我明白这个异常,但我的方法参数是对象数组。如果我删除阵列比我得到NoSuchMethod Exception

如何解决这个问题?

回答

2

您必须通过一类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 
+0

伟大的观察,它解决了编译时问题。但我现在得到这个'java.lang.reflect.InvocationTargetException'。你能指导我吗?同时我会接受这个答复与upvote。 :) – 2013-04-05 10:06:56

+0

@Anto'InvocationTargetException'意味着该方法的实现抛出一个错误。抓住你的代码,调用'getCause()',看看你的例外的真正原因是什么。此时,问题将出现在帖子顶部的段中,或者在您从'newInstance()'调用的默认构造函数中。 – dasblinkenlight 2013-04-05 10:25:36