在 Java 的 Project Valhalla 上下文中,我如何一般初始化 value type使用默认值?
最初,我认为将 null
分配给任何值类型都会执行此初始化。但是,this question的答案和评论清楚地表明 null
是一个引用,因此它与值类型无关(正是因为值类型不是引用,而是直接值)。
例如如果我有一个带有 StringValueType name
和 DateValueType dateOfBirth
属性的 Person
值类型(这里 dateOfBirth
将是一个嵌套值类型包含 int year
、int month
和 int day
属性),我如何初始化我的 Person
值类型 < strong>以通用方式,以便其属性的值为 ""
for name
和 (0, 0, 0)
(或相应的默认值)分别为 dateOfBirth
?
为了更清楚,如果这是 C,我会这样做:
memset(myPersonStructVariable, 0, sizeof(Person));
或者在现代 C 中:
struct Person myPersonStructVariable = {0};
最佳答案
aconst_null
字节码的值类型(即 null
,这将是引用类型的默认值)是 vdefault
字节码.来自最小值类型规范:
Operation
Push the default value of a direct value class type
Format
vdefault indexbyte1 indexbyte2
...
Description
The unsigned indexbyte1 and indexbyte2 are used to construct an index into the run-time constant pool of the current class (2.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The run-time constant pool item at that index must be a symbolic reference to a direct value class type (4.4.1). The type is resolved (5.4.3.1).
The named class is initialized (5.5) if that class has not already been initialized. The default value (2.3.5) of the direct value class type is pushed onto the operand stack.
和 2.3.5:
2.3.5 Direct Value Class Types
...
The default value of a direct value class type is a class instance whose fields store the default values of their respective types. There is no special null value of a direct value class type.
引自 this presentation说:
[A default value] which is really a value of the right width, with all 0s inside.
所以这类似于您在 C 语言中使用 memset(myStructVar, 0, size)
所做的事情。
目前没有对值类型的语言支持,所以我们不能说是否会有类似 null
字面量的东西返回值类型的默认值(例如 MyValueType x = default(MyValueType)
或类似的东西),但字节码存在。该演示文稿还展示了如何使用方法句柄来调用 vdefault
。或者,您必须旋转字节码。
将字段初始化为用户定义的值(例如 ""
for StrinValueType
)可能只是通过调用构造函数(或等效值类型)发生。但目前还不清楚,所以我们只能推测。
此外,请在此处查看 valhalla vm 原型(prototype)的最新草案:http://mail.openjdk.java.net/pipermail/valhalla-dev/2017-December/003631.html
关于java - 如何使用默认值一般地初始化值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48709375/