Java可变参数函数参数

我有一个接受可变数量参数的函数:

foo (Class... types); 

其中我得到了一定数量的类类型。 接下来,我想要一个function

 bar( ?? ) 

这也将接受可变数量的参数,并且能够validation变量与foo中指定的相同数字(很容易)和相同类型(硬部分)。

我怎样才能做到这一点?

编辑:澄清一下,电话可能是:

 foo (String.class, Int.class); bar ("aaa", 32); // OK! bar (3); // ERROR! bar ("aa" , "bb"); //ERROR! 

此外,foo和bar是同一类的方法。

像这样的东西:

 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; } 

例如:

 test.foo(String.class, Integer.class); test.bar("Hello", 10); // Returns true test.bar("Hello", "there"); // Returns false test.bar("Hello"); // Returns false 

(显然你会想要改变报告结果的方式......可能使用无效数据的例外。)