33

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.

Amir Rachum
  • 76,817
  • 74
  • 166
  • 248
  • I didn't understand your requirement. What do you mean by 'the same number as was specified in foo' ? There is no such number. Every call to foo can be with different number of arguments. – duduamar Apr 14 '10 at 06:19
  • 1
    The oracle documentation describes arbitrary parameters as "varargs": http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html. Basically just an array, as it is in ruby and other programming languages. – JohnMerlino Jun 13 '14 at 20:53

1 Answers1

47

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194