Why does the Boolean object have a public constructor in Java?

前端 未结 5 1615
逝去的感伤
逝去的感伤 2021-01-03 20:58

Documentation for the constructor new Boolean(boolean value) in Java states:

Note: It is rarely appropriate to use this constructor. Unle

相关标签:
5条回答
  • 2021-01-03 21:23

    valueOf() only got added in Java 1.4, so it would appear that the constructors exist for backwards compatibility.

    This ticket explains the reasons for not deprecating the constructors:

    Due to the disruption deprecating an API can have, currently an API has to be "actively hazardous" to be deprecated, like Thread.stop. While the use this constructor is certainly ill-advised, it doesn't rise (or sink) to the standard of hazardousness to be deprecated in the JDK. In the future we may add a "denigration" facility to mark API elements that aren't quite so bad that they should be deprecated, but shouldn't be used in most cases. This constructor would be a good candidate for denigration.

    I can't think of a realistic scenario where using Boolean constructors would be the best way to do something useful.

    0 讨论(0)
  • 2021-01-03 21:25

    The reason it hasn't been deprecated is that Java maintains backwards compatibility to version 1.0

    I can't think of a good reason to use the constructor.

    0 讨论(0)
  • 2021-01-03 21:30

    Usually, you will want to use valueOf(boolean) or even the Boolean.TRUE / Boolean.FALSE constants directly.

    But think of a scenario where you want to use a private Boolean variable as a monitor for synchronizing threads. There you will need to make sure you use your own instance and have full control of it.

    0 讨论(0)
  • 2021-01-03 21:39

    Another, not necessarily good reason would probably be to simply keep it consistent with the other native wrappers.

    0 讨论(0)
  • 2021-01-03 21:42

    As of Java 9, the Boolean(boolean) constructor >>is<< deprecated; see javadoc.

    For those who care about the history, there was a longstanding bug that called for the deprecation of the constructor. It was formally proposed in JEP 277 along with a number of other deprecations.

    0 讨论(0)
提交回复
热议问题