Java 将数组读入第二个数组
我有一个对象[],我需要将类型读入类[],然后我将使用这个方法Java 将数组读入第二个数组,java,arrays,methods,Java,Arrays,Methods,我有一个对象[],我需要将类型读入类[],然后我将使用这个方法 public static void invokeMethod(String className, String methodName, Class<?>[] paramTypes, Object[] params) { try { Class<?> commandclass = Class.forName(className); Method met
public static void invokeMethod(String className, String methodName,
Class<?>[] paramTypes, Object[] params) {
try {
Class<?> commandclass = Class.forName(className);
Method method = commandclass.getMethod(methodName, paramTypes);
method.invoke(method, params);
} catch (NoSuchMethodException | SecurityException
| ClassNotFoundException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
稍后在代码中:
invokeMethod("com.cjcl.commands.NewCommand", "command", (Class<?>[]) classes.toArray(), params.toArray());
要尝试的一些修改:
ArrayList<Object> params = new ArrayList<Object>();
int i = 1;
while(true){
String str = input.substring(input.indexOf(" ", i), input.indexOf(" ", i + 1));
if(str.equalsIgnoreCase(" ")){
break;
}
params.add(i, str);
i++;
}
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
// Move the toArray call outside the loop, otherwise it's rebuilding the parameters array each time.
Object[] paramsArray = params.toArray()
int paramsArrayLength = paramsArray.length;
// EDIT: Changed to j++
// This for loop needs to be j < paramsArrayLength.
for(int j = 0; j < paramsArrayLength; j++){
classes.add(paramsArray[j].getClass());
}
最有可能的是,混淆的比较运算符是您的问题。既然你有一个比这更大的,它就不执行了。另外,您没有向集合中添加任何内容,因此toArray几乎肯定会尝试从空集合中生成一个数组
基于您正在初始化i=1,并且您的异常索引超出范围1,我还假设while循环中的代码没有执行。您是否有任何示例代码可以帮助您完成这项任务?我尝试过for循环和ArrayLists,但我无法使数组没有空值。这就是我尝试使用arraylist时遇到的问题?我如何获得无空值valuesjava.lang.IndexOutOfBoundsException:索引:1,大小:0
ArrayList<Object> params = new ArrayList<Object>();
int i = 1;
while(true){
String str = input.substring(input.indexOf(" ", i), input.indexOf(" ", i + 1));
if(str.equalsIgnoreCase(" ")){
break;
}
params.add(i, str);
i++;
}
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
// Move the toArray call outside the loop, otherwise it's rebuilding the parameters array each time.
Object[] paramsArray = params.toArray()
int paramsArrayLength = paramsArray.length;
// EDIT: Changed to j++
// This for loop needs to be j < paramsArrayLength.
for(int j = 0; j < paramsArrayLength; j++){
classes.add(paramsArray[j].getClass());
}