我可以通过一个数组作为参数传递给在Java可变参数的方法? [英] Can I pass an array as arguments to a method with variable arguments in Java?
问题描述
我希望能够创造像一个函数:
I'd like to be able to create a function like:
class A {
private String extraVar;
public String myFormat(String format, Object ... args){
return String.format(format, extraVar, args);
}
}
这里的问题是, ARGS
在方法视为对象[]
myFormat
,因而是一个单一的参数的String.format
,而我想每一个对象
在 ARGS
来作为一个新的参数传递。由于的String.format
还具有可变参数的方法,这应该是可能的。
The problem here is that args
is treated as Object[]
in the method myFormat
, and thus is a single argument to String.format
, while I'd like every single Object
in args
to be passed as a new argument. Since String.format
is also a method with variable arguments, this should be possible.
如果这是不可能的,有像的String.format方法(字符串格式,对象[]参数)
?在这种情况下,我可以用一个新的数组prePEND extraVar
到 ARGS
,并传递给该方法。
If this is not possible, is there a method like String.format(String format, Object[] args)
? In that case I could prepend extraVar
to args
using a new array and pass it to that method.
推荐答案
的基本类型可变参数的方法函数(对象...参数)
的是的函数(对象[]参数)
。孙加可变参数以这种方式preserve向后兼容。
The underlying type of a variadic method function(Object... args)
is function(Object[] args)
. Sun added varargs in this manner to preserve backwards compatibility.
所以,你应该能够prePEND extraVar
到 ARGS
并调用的String.format(格式参数)
。
So you should just be able to prepend extraVar
to args
and call String.format(format, args)
.
这篇关于我可以通过一个数组作为参数传递给在Java可变参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!