简体   繁体   English

有没有办法在Java中重载Integer取消装箱方法?

[英]Is there any way to overload the Integer unboxing method in Java?

I am trying to determine if the unboxing method Java uses can be modified. 我试图确定是否可以修改Java使用的拆箱方法。 The purpose of this is to be able to do: 这样做的目的是能够做到:

class IInteger extends Integer {
  @Override
  public int unboxToPrimitive(){
    return ++val;
  }
}

IInteger i = 10;
System.out.print(i); // 11

That is, overloading the method and having it return ++val instead of val. 也就是说,重载方法并让它返回++ val而不是val。

No. It isn't possible, first Integer is final and cannot be sub-classed. 不可以。首先, Integerfinal ,不能分类。 Second, you can't overload operators in Java. 其次,你不能在Java中重载运算符。 Next, you can't have autoboxing for custom types. 接下来,您无法为自定义类型进行自动装箱。 Finally, you aren't actually using unboxing in your println (you can call print on a reference type). 最后,您实际上并没有在println使用拆箱(您可以在引用类型上调用print )。

However , if I understand what you really want, you could use an AtomicInteger and incrementAndGet() (instead of get() and change your other methods as necessary). 但是 ,如果我理解你真正想要的东西,你可以使用AtomicIntegerincrementAndGet() (而不是get()并根据需要更改你的其他方法)。

不,你甚至无法扩展java.lang.Integer因为它是一个最终的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM