Possible to disable Java autoboxing?

大城市里の小女人 提交于 2020-01-03 18:51:13

问题


The "Generics (Updated)" Java tutorial at:

http://docs.oracle.com/javase/tutorial/java/generics/types.html

defines a simple Box class:

public class Box {
    private Object object;

    public void set(Object object) { this.object = object; }
    public Object get() { return object; }
}

and states:

Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types.

Every primitive I pass to the set method works without compilation error. Is there any way to prevent the autoboxing that automatically wraps the primitive if I did want it to break? And more generally: is there a way to manually prevent autoboxing? I'm using Java 7.


回答1:


is there a way to manually prevent autoboxing?

The only sure way would be use a version of Java earlier Java 5 when autoboxing was introduced. That would be a really bad idea.

(Or maybe compiling with a "-source" flag that specifies Java 1.4 source compatibility would do it. Though you would also lose a LOT of other modern Java language features: generics, enums, etcetera.)

Autoboxing / unboxing is a fundamental part of the modern Java language and it can't be turned off and on at will.




回答2:


No, there is not. A primitive type provided where a reference type is expected will be boxed automatically (provided the types match).



来源:https://stackoverflow.com/questions/26568608/possible-to-disable-java-autoboxing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!