如何使用默认值一般地初始化值类型?

How to generically initialize a value type with its default value?

在 Java 的 Project Valhalla, how can I generically initialize a value type 及其默认值的上下文中?

最初,我认为将 null 分配给任何值类型都会执行此初始化。然而,的答案和评论清楚地表明null是一个reference,所以它与值类型无关(正是由于以下事实值类型不是引用,而是直接值。

例如如果我有一个具有 StringValueType nameDateValueType dateOfBirth 属性的 Person 值类型(此处 dateOfBirth 将是包含 int yearint monthint day 属性),我如何初始化我的 Person 值类型 以通用方式 以便其属性的值是 "" for name(0, 0, 0)(或相应的默认值)分别为dateOfBirth

为了更清楚,如果这是 C,我会这样做:

memset(myPersonStructVariable, 0, sizeof(Person));

或者在现代 C 中:

struct Person myPersonStructVariable = {0};

aconst_null 字节码的值类型(即 null,这将是引用类型的默认值)是 vdefault 字节码。来自最小值类型规范:

6.5 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 文字的东西 return 值类型的默认值(例如 MyValueType x = default(MyValueType) 或类似的东西),但字节码存在。该演示文稿还展示了如何使用方法句柄来调用 vdefault。或者,您必须旋转字节码。

将字段初始化为用户定义的值(例如 "" 对应 StrinValueType)可能只是通过调用构造函数(或等效的值类型)来实现。但目前确实还不清楚,所以我们只能推测。


此外,请在此处查看 valhalla vm 原型的最新草案:http://mail.openjdk.java.net/pipermail/valhalla-dev/2017-December/003631.html