25

有什么方法可以对我创建的类使用自动装箱吗?例如,我有这个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");
    }
}

现在,UnsignedInteger i = new UnsignedInteger(88);工作得很好,但是有什么办法可以编译:UnsignedInteger i = 88;?它不会适合我。提前致谢!

4

4 回答 4

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.

于 2013-07-12T16:39:40.233 回答
12

不,不幸的是。自动装箱转换(根据JLS §5.1.7)仅为标准原始包装类定义。

于 2013-07-12T16:37:52.747 回答
1

简而言之:不,这是不可能的。为此,您需要运算符重载,这在 Java 中不可用。见链接

于 2013-07-13T06:44:37.890 回答
0

如果您使用 Groovy,您可以通过实现 asBoolean 方法来设置布尔行为:http: //groovy-lang.org/semantics.html#_customizing_the_truth_with_asboolean_methods

例子:

class Color {
    String name

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

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

我知道这不是纯 Java,而是编译为字节码并在 JVM 上运行。

于 2018-03-18T18:09:40.000 回答