方法原型中varargs的多个对象类型?

exe*_*ifs 13 java variadic-functions

我正在尝试编写可以使用任意数量的整数和字符串调用的Java函数的原型:

myMethod(1, 2, 3, "Hello", "World"); // Valid call
myMethod(4, "foo", "bar", "foobar"); // Valid call
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望以任何顺序(并且可能混合)给出整数和字符串:

myMethod(1, "Hello", 2, "World", 3); // Valid call
Run Code Online (Sandbox Code Playgroud)

我想过使用varargs,但原型中只能有一个.我的另一个想法是使用以下原型:

public void myMethod(Object ... objs) { [...] }
Run Code Online (Sandbox Code Playgroud)

...但我觉得如果用预期类型以外的东西调用它应该有一个编译错误.当然,instanceof可以执行运行时检查(),但这不是一个非常优雅的解决方案,不是吗?

你会怎么做?

Sam*_*war 10

如果你想要它是类型安全的,我会用这个:

public myMethod(Thing<?>... thing) { ... }
Run Code Online (Sandbox Code Playgroud)

然后创建你的Thing类:

public interface Thing<T> {
    public T value();
}

public class IntThing implements Thing<Integer> {
    private final int value;

    public IntThing(int value) {
        this.value = value;
    }

    public Integer value() {
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

我会让你想象一下如何编写StringThing.显然,使用比"Thing"更好的名字,但我无法帮助你.

然后,您创建两个静态方法:

public static Thing<Integer> thing(int value) {
    return new IntThing(value);
}

public static Thing<String> thing(String value) {
    return new StringThing(value);
}
Run Code Online (Sandbox Code Playgroud)

然后在调用中将每个对象包装为thing:

myMethod(thing(1), thing(2), thing(3), thing("Hello"), thing("World"));
Run Code Online (Sandbox Code Playgroud)

乱?对.不幸的是,Java没有能力像其他语言一样隐藏这些东西.Scala隐含的defs会帮助你,但这带来了一大堆其他问题.就个人而言,我会选择instanceof检查,但这个检查确保您的代码在编译时是安全的.


Jes*_*per 7

Java编程语言中无法使其工作,因此您可以传递任意数量的字符串和整数,并在传递除字符串或整数之外的其他内容时让编译器发出错误.