我创建的类可以进行自动装箱吗? [英] Is autoboxing possible for the classes I create?

查看:127
本文介绍了我创建的类可以进行自动装箱吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为我创建的类使用自动装箱?例如,我有 Number 的子类。

  public class UnsignedInteger扩展数字{
int n;

public UnsignedInteger(int n){
if(n> = 0)
this.n = n;
else
抛出新的IllegalArgumentException(仅支持正整数);
}
}

现在, UnsignedInteger i =新的UnsignedInteger(88); 工作得很好,但有没有办法进行编译: UnsignedInteger i = 88; ?它不适合我。提前致谢!

解决方案

简而言之,没有。没有办法让它编译。<​​/ p>

Java只定义了一组有限的预定义拳击转换。



来自 JLS,部分5.1.7


拳击转换将基本类型的表达式转换为引用类型的相应表达式。具体来说,以下九个转换称为装箱转换:




  • 从类型布尔值到类型布尔


  • 从类型字节到类型字节


  • 从短类型到短类型


  • 从char类型到类型Character


  • 从int类型到Integer类型


  • 从类型long到类型Long


  • 从类型float到类型Float


  • 从double类型到double类型


  • 从null类型到null类型



此外,有人可能会考虑重载 = 运算符来执行此转换,但是在Java中不支持运算符重载,这与C ++不同,这是可能的。



所以你的转换不可能用Java。


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!

解决方案

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.

这篇关于我创建的类可以进行自动装箱吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆