正确识别一个int []通过为可变参数的参数 [英] Correctly recognise an int[] passed as a varargs parameter

查看:118
本文介绍了正确识别一个int []通过为可变参数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有似乎是自动装箱和原始阵列的可变参数系统之间的边缘情况。有没有解决这个干净的(即非反射)的方式?

There seems to be an edge case between the autoboxing and the varargs system for primitive arrays. Is there a clean (i.e. non-reflection) way around this?

示例:

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 []打印不正确 - 它似乎是被包装成对象[] ,其首先看重的是我的 INT [] 。一切似乎很好地框。

Notice that the int[] does not print correctly - it seems to be being boxed into an Object[] whose first value is my int[]. Everything else seems to box nicely.

我要的 INT [] 调用正确打印不破坏他人。

I want the int[] call to print correctly without breaking the others.

P.S。如果你能够通过反射做到这一点,通过各种手段发布。我只是preFER不使用它。

P.S. If you can do it by reflection, by all means post. I'd just prefer not to use it.

推荐答案

不幸的是,你需要添加

String text;
if (ts[0] instanceof int[])
    text = Arrays.toString((int[]) ts[0]);
else
    text = Arrays.toString(ts);

我怀疑有一个Apache公共库为你做这一点,但我不知道是哪一个。

I suspect there is an Apache common library to do this for you, but I don't know which one.

这篇关于正确识别一个int []通过为可变参数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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