问题
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