问题描述
这是另一个问题我如何用Java做这个?在Python中,我可以使用'*'符号解压缩参数,如下所示:
Here's another question of "How would I do this in Java?" In Python, I can use the '*' symbol to unpack arguments like so:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Java支持使用 ... args
语法获取args列表,但有没有办法(可能使用Reflection库?)解压缩其他函数?
Java supports getting a list of args with ...args
syntax, but is there a way (perhaps using the Reflection libraries?) to unpack those for some other function?
推荐答案
public void printStrings(String... strings)
{
// the strings parameter is really a String[].
// You could do anything to it that you normally
// do with an array.
for(String s : strings){
System.out.println(s);
}
}
可以像这样调用:
String[] stringArray = new String[10];
for(int i=0; i < stringArray.length; i++){
stringArray[i] = "String number " + (i+1);
}
printStrings(stringArray);
...
语法真的是语法数组的糖。
The ...
syntax is really syntactic sugar for arrays.
Java没有你描述的功能,但你可以用几种方法伪造它。
Java doesn't have the facility that you describe, but you could fake it several ways.
我认为最接近的近似意味着使用varargs重载你想要以这种方式使用的任何函数。
I think the closest approximation means overloading any function that you want to use in that fashion using varargs.
如果你有一些方法:
public void foo(int a, String b, Widget c) { ... }
你可以重载它:
public void foo(Object... args) {
foo((Integer)args[0], (String)args[1], (Widget)args[2]);
}
但这真的很笨拙且容易出错并难以维护。
But this is really clumsy and error prone and hard to maintain.
更一般地说,你可以使用反射来使用任何参数调用任何方法,但它也有很多陷阱。这是一个错误的,不完整的例子,说明它如何变得非常快:
More generically, you could use reflection to call any method using any arguments, but it's got a ton of pitfalls, too. Here's a buggy, incomplete example of how it gets ugly really fast:
public void call(Object targetInstance, String methodName, Object... args) {
Class<?>[] pTypes = new Class<?>[args.length];
for(int i=0; i < args.length; i++) {
pTypes[i] = args[i].getClass();
}
Method targetMethod = targetInstance.getClass()
.getMethod(methodName, pTypes);
targetMethod.invoke(targetInstance, args);
}
这篇关于Java解包参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!