这个问题困扰了我两天。我有一个名为Test的类,其中包含一系列testN方法,而且我还会为该类添加更多的test*方法。以下是示例代码:
public class Test {
public void test1(String a, int b, boolean c){
System.out.println("a="+a+" "+b+ " c="+c);
}
public void test3(Test test){
System.out.println(test.toString());
}
public void run(Object... objs){
//First way...
if(objs.length>=3){
test1((String)objs[0], (int)objs[1], (boolean)objs[2]);
}else if(objs.length <3 ){
test3((Test)objs[0]);
}
//Second way?
MethodType type1 = MethodType.methodType(void.class, String.class, int.class, boolean.class);
if(objs.length>=3){
//How to tranform first 3 elements of objs to a list (String, int, boolean)
Object[] t = Arrays.copyOfRange(objs, 0, type1.parameterCount());
test1(???);
}
MethodType type3 = MethodType.methodType(void.class, Test.class);
if(objs.length < 3 ){
}
}
public static void main(String[] args){
Test test = new Test();
test.run("String", 3, false, 5,7);
test.run(test,1);
}
}
方法
run(Object... objs)
是该类的主要入口,它接受可变参数列表。在方法 run
中,根据 objs 的长度(objs 被识别为数组),它会调用不同的 test* 方法。对于我来说,问题在于如何将第二种方式中的
Object[] t
作为 test1
方法的可变参数列表进行传递?第一种方式是处理-写入方式,当添加更多的 test*
方法时并不实用。 Object[] t
是一个数组,它只是一个对象,而 test1
需要三个参数。我正在寻找一种可以将数组转换为方法调用参数列表的方法。