问题描述
有没有办法为我创建的类使用自动装箱?例如,我有 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;
?它不适合我。提前致谢!
简而言之,没有。没有办法让它编译。
Java只定义了一组有限的预定义拳击转换。
来自:
此外,有人可能会考虑重载 =
运算符来执行此转换,但是在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:
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.
这篇关于我创建的类可以进行自动装箱吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!