为什么null不是编译时常量? [英] Why isn't null a compile time constant?
问题描述
因此,如果我有一个静态最终对象CONSTANT = null
,出于某种原因我会在另一段代码中引用它,例如 doSomething(CONSTANT )
,它不会在编译期间内嵌到代码中。所以编译后不是 doSomething(null)
,而是 doSomething(CONSTANT)
。
So if I have a static final Object CONSTANT = null
, for some reason if I reference that in another piece of code like doSomething(CONSTANT)
, it won't be in-lined onto the code during compilation. So instead of being doSomething(null)
after being compiled, it would be doSomething(CONSTANT)
.
推荐答案
您的 CONSTANT
不是编译时常量,因为JLS 表示不是。可以在常量表达式中使用的唯一类型是基本类型和 String
。
Your CONSTANT
is not a compile time constant because the JLS says it is not. The only types that can be used in constant expressions are the primitive types and String
.
它的意义是 Object
实例(通常)具有语义上重要的对象标识,可将其与其他 Object
实例区分开来。此对象标识不能在类文件中编码...或者至少,它不能使用当前的类文件格式进行编码。 (如果可以,会有各种其他问题......)
The sense of it is that an Object
instance (in general) has a semantically significant object identity that distinguishes it from other Object
instances. This Object identity cannot be encoded in a class file ... or at least, it can't be encoded with the current classfile formats. (And if it could, there would be all sorts of other problems ...)
值 null
可以(理论上)作为一个特例处理,除了没有太多意义。具体来说,您不能在语言学角度需要(或有利)编译时间常数的任何上下文中使用 null
。例如:
The value null
could (in theory) be handled as a special case, except that there is not a great deal of point. Specifically, you can't use null
in any of the contexts where a "compile time constant" is required (or advantageous) from the linguistic perspective. For instance:
- 你不能将
null
作为case
表达。 - 由于
==
对于引用类型不是常量表达式,你可以不能将它用于Java条件编译习惯用法,如果,则使用常量表达式作为条件的。 (除了
null == null
不是一个有用的条件......)
- You can't have
null
as acase
expression. - Since
==
for reference types is not a constant expression, you can't use it for the Java "conditional compilation" idiom involving anif
with a constant expression as a condition. (And besidesnull == null
is not a useful condition ...)
就内联而言,虽然常量不能在字节码中内联(因为关于常量表达式是什么的JLS规则),JIT编译器的优化器将被允许这样做,并且可能实际上是这样做的......如果有明显的性能优势。
As far as inlining is concerned, while the "constant" cannot be inlined in the bytecodes (because of the JLS rules about what a "constant expression" is), the JIT compiler's optimizer would be permitted to do this, and may actually do it ... if there are tangible performance benefits.
参考:
- JLS 15.28 - Constant Expressions
这篇关于为什么null不是编译时常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!