[英]Method with multiple inputs java
I have a interface and in the interface I want to declare a method such that it can take any number of objects as input.我有一个接口,我想在接口中声明一个方法,以便它可以将任意数量的对象作为输入。
Something like this:像这样的东西:
interface Implementable{
public ReturnObj doIt(objects ....);
}
Please advise请指教
The correct syntax would in your case be:在您的情况下,正确的语法是:
interface Implementable{
public ReturnObj doIt(Object... objs);
}
Official documentation for var-arg methods is found here .可在 此处找到 var-arg 方法的官方文档。
I was about to ask the difference between varargs and passing an array,我正要问可变参数和传递数组的区别,
Varargs gets compiled into an argument of an array-type. Varargs 被编译成数组类型的参数。 The only difference is with the vararg syntax, method calls such as唯一的区别在于 vararg 语法,方法调用如
doIt("hello", "world");
will be compiled into会被编译成
doIt(new Object[] { "hello", "world" });
In other words, given a declaration such as换句话说,给定一个声明,例如
public ReturnObj doIt(Object[] objs);
you'll have你会有
doIt(new Object[] { "hello", "world" }); // works fine
doIt("hello", "world"); // won't compile
while given the var-arg declaration, both method calls will compile and be equivalent.虽然给出了 var-arg 声明,但两个方法调用都将编译并且是等效的。
Pass an array:传递一个数组:
public ReturnObj doIt(Object[] input);
or use the equivalent varargs expression或使用等效的可变参数表达式
public ReturnObj doIt(Object... input);
Example:例子:
interface Implementable{
public ReturnObj doIt(Object... object);
}
Alternatively (which I should prefer, especially in Web Services design):或者(我应该更喜欢,尤其是在 Web 服务设计中):
interface Implementable{
public ReturnObj doIt(Object[] object);
}
You forgot to ask a question, but assuming you want to know how to declare a method which takes variable number of arguments, check out this link:您忘了问一个问题,但假设您想知道如何声明一个采用可变数量 arguments 的方法,请查看此链接:
http://download.oracle.com/javase/1,5.0/docs/guide/language/varargs.html http://download.oracle.com/javase/1,5.0/docs/guide/language/varargs.html
So it would be所以它会是
interface Implementable{
public ReturnObj doIt(Object... objects);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.