我正在尝试编写可以使用任意数量的整数和字符串调用的 Java 函数的原型(prototype):
myMethod(1, 2, 3, "Hello", "World"); // Valid call
myMethod(4, "foo", "bar", "foobar"); // Valid call
理想情况下,我希望以任何顺序(可能混合)给出整数和字符串:
myMethod(1, "Hello", 2, "World", 3); // Valid call
我想过使用可变参数,但原型(prototype)中只能有一个。我的另一个想法是使用以下原型(prototype):
public void myMethod(Object ... objs) { [...] }
...但我觉得如果使用预期类型之外的其他内容调用它,应该会出现编译错误。当然,可以执行运行时检查 (instanceof
),但这不是一个非常优雅的解决方案,对吗?
你会怎么做?
最佳答案
如果你希望它是类型安全的,我会这样做:
public myMethod(Thing<?>... thing) { ... }
然后创建您的 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;
}
}
我会留给您想象如何编写 StringThing。显然,使用比“Thing”更好的名称,但我无法帮助您。
然后你创建两个静态方法:
public static Thing<Integer> thing(int value) {
return new IntThing(value);
}
public static Thing<String> thing(String value) {
return new StringThing(value);
}
然后将每个对象包装在对 thing
的调用中:
myMethod(thing(1), thing(2), thing(3), thing("Hello"), thing("World"));
凌乱?是的。不幸的是,Java 没有像其他语言那样隐藏这些东西的能力。 Scala 的隐式 defs 会在这里帮助你,但这会带来一大堆其他问题。就我个人而言,我会选择 instanceof
检查,但这将确保您的代码在编译时是安全的。
关于java - 方法原型(prototype)中可变参数的多个对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6322129/