如何定义一个可以在java中获取任意参数的方法? [英] How to define a method that can take arbitrary arguments in java?
问题描述
如何定义一个可以在java中获取任意参数的方法?有演示吗?
How to define a method that can take arbitrary arguments in java? Is there a demo?
推荐答案
varargs 在Java 5中引入。
varargs were introduced in Java 5.
例如:
public String join(String... parts);
这实际上是一个快捷方式:
This is actually a shortcut for:
public String join(String[] parts);
parts
参数用作数组在方法中,但可以在不构造数组的情况下调用该方法(如 obj.join(new String [] {part1,part2,part3})
)
the parts
parameter is used as an array in the method, but the method can be called without constructing an array (like obj.join(new String[] {part1, part2, part3})
)
但是要非常小心,因为可能会产生歧义。例如:
However be very careful with this, because ambiguities can arise. For example:
public void write(String author, String... words);
public void write(String... words);
如果 obj.write(Mike,跳)
?编译器足够聪明,可以检测出歧义,但是我遇到过某些编译器没有发现这些问题的情况(无法准确回忆)
Which method will be called if obj.write("Mike", "jumps")
? The compiler is clever enough to detect the ambiguity, but I've had cases when some compilers did not spot such problems (can't recall exactly)
使用varargs是实用的当物体属于同一类型或至少具有相同的功能目标时。如果你想要不同的论点。例如:
Using varargs is practical when the objects are of the same type, or at least with the same functional aim. If you want different arguments. For example:
public String publishBook(String title, [String author],
[String isbn], [boolean hardcover]); // [..] would mean optional
然后你需要重载你的方法
这篇关于如何定义一个可以在java中获取任意参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!