我可以将数组作为参数传递给 Java 中带有可变参数的方法吗? [英] Can I pass an array as arguments to a method with variable arguments in Java?
问题描述
我希望能够创建一个函数,例如:
class A {私人字符串 extraVar;public String myFormat(String format, Object ... args){返回 String.format(format, extraVar, args);}}
这里的问题是 args
在方法 myFormat
中被视为 Object[]
,因此是 的单个参数>String.format
,而我希望 args
中的每个 Object
都作为新参数传递.由于 String.format
也是一个带有可变参数的方法,所以这应该是可能的.
如果这是不可能的,是否有类似 String.format(String format, Object[] args)
的方法?在这种情况下,我可以使用新数组将 extraVar
前置到 args
并将其传递给该方法.
a> 方法 function(Object... args)
is function(Object[] args)
.Sun 以这种方式添加了可变参数以保持向后兼容性.
所以你应该能够在 extraVar
前面加上 args
并调用 String.format(format, args)
.
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);
}
}
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.
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.
The underlying type of a variadic method function(Object... args)
is function(Object[] args)
. Sun added varargs in this manner to preserve backwards compatibility.
So you should just be able to prepend extraVar
to args
and call String.format(format, args)
.
这篇关于我可以将数组作为参数传递给 Java 中带有可变参数的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!