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.
Methods which uses variable arguments (varargs, arguments with three dots) are known as variadic functions.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With