简体   繁体   中英

Java variadic function parameters

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM