Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to disable Java autoboxing?

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.

like image 679
gcbound Avatar asked Jan 09 '23 13:01

gcbound


1 Answers

is there a way to manually prevent autoboxing?

The only sure way would be use a version of Java earlier than Java 5, which was when autoboxing was introduced.

Or maybe compiling with a -source flag that specifies Java 1.4 source compatibility would do it. Note: this won't work with javac in Java 9 or later, because support for -source less or equal to 5 has not been removed from javac.

Doing either would be a really bad idea for anything other than experimentation. You would also lose a LOT of other important Java language features by reverting to the Java 1.4 level; e.g. generics, enums, and so on.

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

like image 122
Stephen C Avatar answered Jan 18 '23 22:01

Stephen C