重新创建方法调用(使用反射)

时间:2013-05-17 07:50:08

标签: java reflection

如何重新创建方法调用?当我得到的是方法列表,由getDeclaredMethods()获得,并转换为HashMap<String,Method>及其参数'Classes的列表,由getParameterTypes()获得。

假设我从用户那里得到一个字符串,我想调用它:

"print(3,"Hello World!",true,2.4f)"

方法print(int,String,boolean,float)是getMethods()数组的一部分。我无法弄清楚如何编写调用。到目前为止,这就是我得到的:

private static final Pattern functionCall = Pattern.compile(String.format("^%s\\(%s?\\)$", "(\\w+)", "(.*)"));

if( (m = functionCall.matcher(line)).find() ) {
    String function = m.group(1); // in this example = "print"
    String arguments = m.group(2); // in this example = "3,\\"Hello World!\\",true,2.4f"
    if( methods.containsKey(function) ) {
        Method method = methods.get(function);
        Class<?>[] paramsExpected = method.getParameterTypes();
        String [] paramsActual = arguments.split(",");
        if( paramsExpected.length != paramsActual.length ) {
            throw new IllegalArgumentException(function + ": bad number of arguments");
        }
        for( Class<?> param: paramsExpected) {
            ???????
        }
        method.invoke(context, ??????);

要非常清楚,我事先并不知道用户将输入什么字符串,我必须根据可用的方法及其参数进行检查,如果我找到它,那么我必须使用参数调用它由用户提供。

1 个答案:

答案 0 :(得分:2)

这就是你需要做的。一种选择是使用BeanUtils的ConverterUtils.convert方法将字符串转换为特定类型的对象。这适用于内置类型。

    Object[] args = new Object[paramsExpected.length];
    int i = 0;  
    for( Class<?> param: paramsExpected) {
        args[i] = convertStringToType(paramsActual[i], param);
        i  = i +1;
    }
    method.invoke(context, args);

    Object convertStringToType(String input, Class<?> type) {
      return ConverterUtils.convert(input,type);
    }
相关问题