Java 可变参数函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2635229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java variadic function parameters
提问by Amir Rachum
I have a function that accepts a variable number of parameters:
我有一个接受可变数量参数的函数:
foo (Class... types);
In which I get a certain number of class types. Next, I want to have a function
在其中我得到了一定数量的类类型。接下来,我想要一个功能
bar( ?? )
That will accepts a variable number of parameters as well, and be able to verify that the variables are the same number (that's easy) and of the same types (the hard part) as was specified in foo
.
这也将接受可变数量的参数,并能够验证变量是否与foo
.
How can I do that?
我怎样才能做到这一点?
Edit:to clarify, a call could be:
编辑:澄清一下,电话可能是:
foo (String.class, Int.class);
bar ("aaa", 32); // OK!
bar (3); // ERROR!
bar ("aa" , "bb"); //ERROR!
Also, foo and bar are methods of the same class.
此外, foo 和 bar 是同一类的方法。
采纳答案by Jon Skeet
Something like this:
像这样的东西:
private Class<?>[] types;
public void foo(Class<?>... types)
{
this.types = types;
}
public boolean bar(Object... values)
{
if (values.length != types.length)
{
System.out.println("Wrong length");
return false;
}
for (int i = 0; i < values.length; i++)
{
if (!types[i].isInstance(values[i]))
{
System.out.println("Incorrect value at index " + i);
return false;
}
}
return true;
}
For example:
例如:
test.foo(String.class, Integer.class);
test.bar("Hello", 10); // Returns true
test.bar("Hello", "there"); // Returns false
test.bar("Hello"); // Returns false
(Obviously you'll want to change how the results are reported... possibly using an exception for invalid data.)
(显然,您需要更改报告结果的方式……可能对无效数据使用异常。)