开发者

Java variadic function parameters

开发者 https://www.devze.com 2022-12-26 14:15 出处:网络
I have a function that accep开发者_JAVA技巧ts a variable number of parameters: foo (Class... types);

I have a function that accep开发者_JAVA技巧ts 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消