Java可变参数函数参数 [英] Java variadic function parameters

查看:388
本文介绍了Java可变参数函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受可变数量参数的函数:

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( ?? )

这也将接受可变数量的参数,并且能够验证变量是相同的数字(这很容易)和相同的类型(在 foo 中指定的硬部分。

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.

我该怎么做?

编辑澄清,来电可能是:

foo (String.class, Int.class);
bar ("aaa", 32); // OK!
bar (3); // ERROR!
bar ("aa" , "bb"); //ERROR!

此外,foo和bar是同一类的方法。

Also, foo and bar are methods of the same class.

推荐答案

这样的事情:

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;
}

例如:

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

这篇关于Java可变参数函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆