简体   繁体   English

有没有办法告诉Java编译器不要自动装箱我的原始类型

[英]Is there a way to tell Java compiler not to auto box my primitive type

For example, here are two java methods 例如,这是两个java方法

void test(int... values){}

And

void test(Object... values){}

If I make a call with arguments (1,2,3) , there will be a compile error. 如果我使用参数(1,2,3)进行调用,则会出现编译错误。

Also, I just need the facilities of java varargs, and can not declare my methods with argments int[] or Object[]. 另外,我只需要Java varargs的便利,就不能用argments int []或Object []声明我的方法。

Is it possible? 可能吗?

You can always create the array explicitly: 您始终可以显式创建数组:

foo.test(new int[] { 1, 2, 3 });

This works precisely as the vararg method would, so the bytecode won't even know the difference, and it'll resolve to the int... overload. 这与vararg方法的工作方式完全一样,因此字节码甚至都不知道它们之间的区别,它将解析为int...重载。

The above is essentially equivalent to creating a variable for the int[] , and passing that in: 上面的代码本质上等效于为int[]创建一个变量,并将其传递给:

int[] ints = { 1, 2, 3 };
foo.test(ints);

There isn't any other way to tell the compiler which overload you want. 没有其他方法可以告诉编译器您想要哪个重载。

If you explicitly convert and cast to make the actual arguments exactly match one of the formal argument lists, there is no ambiguity: 如果显式转换并强制转换以使实际参数与形式参数列表之一完全匹配,则不会有歧义:

public class Test {
  public static void main(String[] args) {
    test(new int[] { 1, 2, 3 });
    test((Object[]) new Integer[] { 1, 2, 3 });
  }

  public static void test(int... values) {
    System.out.println("int version called");
  }

  public static void test(Object... values) {
    System.out.println("Object version called");
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM