Is autoboxing possible for the classes I create?
Asked Answered
D

4

25

Is there any way to use autoboxing for the classes I create? For example, I have this subclass of Number.

public class UnsignedInteger extends Number {
    int n;

    public UnsignedInteger(int n) {
        if(n >= 0)
            this.n = n;
        else
            throw new IllegalArgumentException("Only positive integers are supported");
    }
}

Now, UnsignedInteger i = new UnsignedInteger(88); works perfectly fine, but is there any way to make this compile : UnsignedInteger i = 88;? It won't for me. Thanks in advance!

Disendow answered 12/7, 2013 at 16:35 Comment(1)
Good news for this question. I've just filed a feature request to Oracle for adding support for the above syntax. Let's hope it gets accepted.Chopin
B
20

In short, no. There's no way to get that to compile.

Java only defines a limited set of pre-defined boxing conversions.

From the JLS, section 5.1.7:

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:

  • From type boolean to type Boolean

  • From type byte to type Byte

  • From type short to type Short

  • From type char to type Character

  • From type int to type Integer

  • From type long to type Long

  • From type float to type Float

  • From type double to type Double

  • From the null type to the null type

Additionally, one might think of overloading the = operator to perform this conversion, but operator overloading is not supported in Java, unlike in C++, where this would be possible.

So your conversion is not possible in Java.

Borneol answered 12/7, 2013 at 16:39 Comment(1)
We could think that java overloads the operator +,*, or /,- but this actually autoboxing for operating with that. See the oracle spec docs.oracle.com/javase/tutorial/java/data/autoboxing.htmlAllfired
B
12

No, unfortunately. Automatic boxing conversions (as per JLS §5.1.7) are only defined for the standard primitive wrapper classes.

Bashee answered 12/7, 2013 at 16:37 Comment(0)
O
1

In short : No, it's not possible. For this to work, you need operator overloading, which is not available in Java. See link.

Oletaoletha answered 13/7, 2013 at 6:44 Comment(0)
E
0

If you use Groovy, you can set the boolean behavior by implementing the asBoolean method: http://groovy-lang.org/semantics.html#_customizing_the_truth_with_asboolean_methods

Example:

class Color {
    String name

    boolean asBoolean(){
        name == 'green' ? true : false
    }
}

assert new Color(name: 'green')
assert !new Color(name: 'red')

I know this is not plain Java but compiles to bytecode and runs on the JVM.

Eikon answered 18/3, 2018 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.