Java variadic function parameters

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)