Java 中的非大写常量
这个问题关于为什么常量按照惯例,Java 都是大写的,这让我尝试思考反例。
我至少能想到一个(Double.NaN
)。还有其他人吗?
This question about why constants in Java are uppercase by convention made me try to think of counter examples.
I can think of at least one (Double.NaN
). Are there others?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当然,
public final static PrintStream out
(在java.lang.System.out
中)。但这是一个非常好的例外,因为 System.OUT.println 实在是太丑了。此外,大多数时间记录器的初始化如下:
但是,在这两种情况下,这些都不是真正意义上的常量。因此,也许我们可以做出区分:
static
字段是因为它们需要静态访问,而final
字段是因为它们不应在运行时重新分配,因此不一定是< em>常数。Of course,
public final static PrintStream out
(injava.lang.System.out
). But it's a very good exception, becauseSystem.OUT.println
is just ugly.Also, most of the time loggers are initialized as follows:
However, in both cases these are not constants in the true sense of the term. So perhaps we can make a distinction:
Fields that are
static
because they need a static access, andfinal
because they should not be re-assigned at runtime, are not necessarily constants.有很多
serialVersionUID
!ResultSetMetaData
中的其他内容如columnNoNulls
、columnNullable
...DatabaseMetaData
和ICC_Profile
有很多混合大小写的常量。以下是大多数(如果不是全部)JavaSE 常量的列表: 常量字段值
There are lots of
serialVersionUID
!Others in
ResultSetMetaData
likecolumnNoNulls
,columnNullable
...DatabaseMetaData
andICC_Profile
have lots of mixed case constants.Here is a list with most, if not all, JavaSE constants: Constant Field Values
颜色常量,如黑色、红色、绿色等,来自 java.awt.Color 类。
需要注意的是 java.awt.Color 还提供这些常量的大写替代(例如 BLACK、RED、GREEN 等)。
Color constants like black, red, green etc from java.awt.Color class.
It should be noted that java.awt.Color also provides the uppercase alternatives (e.g. BLACK, RED, GREEN etc) of these constants.
java.util.logging.Logger.global 是一个全小写的常量
java.util.logging.Logger.global is a constant with all lowercase
null
、true
和false
。它们可以说是关键字,但当你仔细研究时,它们是分别计算为 0x00、0x01 和 0x00 的常量。null
,true
andfalse
. They are arguably keywords, but when you get down to it, they're constants evaluating to 0x00, 0x01 and 0x00 respectively.数组实例的
长度
。顺便说一句,我看到提到的对象在一方面是“恒定”的示例,即它们的引用不会改变 - 引用是最终静态的,但是当这些对象处于活动状态时;即,当调用这些对象上的方法时,它们的内部属性确实会发生变化。在这些情况下,我不会使用大写命名约定,因为在我看来,对象不是常量。
The
length
of array instances.Btw, I see examples mentioned of objects that are "constant" in one respect, namely their reference does not change - the reference is a final static, but when those objects are active; i.e. their internal attributes do change when methods on these objects are called. In those cases I would not use the UPPERCASE naming convention as the objects are no constants in my view.