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

如何解决这个问题?

4

1 回答 1

2

您需要传递数组的一个类CreateRequisitionRO,而不是类的数组:替换这个

Class[] parames = new Class[1]; 
parames[0] = CreateRequisitionRO.class;

有了这个:

Class parames = CreateRequisitionRO[].class;

另外,由于第二个参数是boolean, not Boolean,所以需要替换

booleanVal = Boolean.class; // The class of the wrapper Boolean

booleanVal = Boolean.TYPE;  // The class of the primitive boolean
于 2013-04-05T09:59:50.050 回答