开发者

How to know if method is taking array as param using reflection

I am trying to invoke the API with the given input parameters. Input params are coming as a List. Now my job is get the API's parameter types one by one and build the required type instance from List. I am able to do for simple java types , List, Set but I am stuck at the array.

Method  method = getMethodFromTheClassBasedOnvalues(  loadedClass,   apiName, numberOfParams);
     Type[] apiMethodParams = method.getGenericParameterTypes();
         List<Type> expectedParamTypes = Arrays.asList(apiMethodArgTypes);
     List<Object> actualValues = // method input.

    List<Object> argsList = new ArrayList<Object>();
    for (int i = 0; i < expectedParamTypes.length; i++) {
        argsList.add(castToRequiredType(expectedParamTypes.get(i),
                actualValues.get(i)));

    method.invoke(loadClass.newInstance(), argsList.toArray());
开发者_如何学编程

The problem comes when I get the method which is of type API (String, String[]) I try to get GenericTypes by calling method.getGenericParameterTypes() which returns and array something like this : [class java.lang.String, class [Ljava.lang.String;] or if one parameter [Ljava.lang.String; Based on this how would I know if its taking Array of String. I see difference is class name is starting after [L and finishes with; but is it guaranteed? Will the bevhiour be same for CustomObject[] also?

Is there any smart way to know if the method is taking an array and to build it lately? Any thoughts in this direction will help.

Thanks in advance.


Try to use

Class[] Mehotd.getParameterTypes()

After that you can call Class.isArray() and determine does this parameter class is array


[L means an array of objects indeed. See for example here. But the best way to check if some class represents an array, is the isArray method.


You haven't shown what castToRequiredType is doing, but if you ever end up casting the Type to Class, you'll be able to use Class.isArray and Class.getComponentType.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜