Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java variadic function parameters

Tags:

java

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.

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.

like image 470
Amir Rachum Avatar asked Apr 14 '10 06:04

Amir Rachum


People also ask

Does Java have variadic functions?

Methods which uses variable arguments (varargs, arguments with three dots) are known as variadic functions.

How do you pass variable length arguments in Java?

A method with variable length arguments(Varargs) in Java can have zero or multiple arguments. Variable length arguments are most useful when the number of arguments to be passed to the method is not known beforehand. They also reduce the code as overloaded methods are not required.

What is Varargs parameter in Java?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs.


1 Answers

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.)

like image 89
Jon Skeet Avatar answered Oct 05 '22 07:10

Jon Skeet