原始数组的自动装箱和可变参数系统之间似乎存在边缘情况。有没有一种干净的(即无反射)方法可以解决这个问题?
示例:
public class Test {
class A<T> {
public void a(T... ts) {
System.out.println(ts.getClass().getCanonicalName() + " of " + ts[0].getClass().getCanonicalName() + " = " + Arrays.toString(ts));
}
}
public void test() {
// These all work fine - presumably all parameters are autoboxed.
new A().a(1, 2, 3);
new A().a(1.0, 2.0, 3.0);
new A().a(1L, 2L, 3L);
// You can even mix them up - which is unexpected.
new A().a(1.0f, 2.0d, 3L);
// Works fine - even though I get a "non-varargs call to varargs method with inexact argument type ..." hint.
new A().a(new Integer[]{1, 1});
// No hint - and doesn't do as intended.
new A().a(new int[]{1, 1});
// Works fine.
new A<Integer>().a(new Integer[]{1, 1});
}
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}
打印
java.lang.Object[] of java.lang.Integer = [1, 2, 3]
java.lang.Object[] of java.lang.Double = [1.0, 2.0, 3.0]
java.lang.Object[] of java.lang.Long = [1, 2, 3]
java.lang.Object[] of java.lang.Float = [1.0, 2.0, 3]
java.lang.Integer[] of java.lang.Integer = [1, 1]
java.lang.Object[] of int[] = [[I@4d815146]
java.lang.Integer[] of java.lang.Integer = [1, 1]
请注意,int[] 无法正确打印 - 它似乎被装箱到一个 Object[]
中,其第一个值是我的 int[]
。其他一切似乎都很好。
我希望 int[]
调用能够正确打印而不破坏其他调用。
附注如果你能通过反射(reflection)做到这一点,那么一定要发帖。我只是不想使用它。
最佳答案
不幸的是,您需要添加
String text;
if (ts[0] instanceof int[])
text = Arrays.toString((int[]) ts[0]);
else
text = Arrays.toString(ts);
我怀疑有一个 Apache 公共(public)库可以为您执行此操作,但我不知道是哪一个。
关于java - 正确识别作为 varargs 参数传递的 int[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16854959/