【发布时间】:2021-01-15 18:45:48
【问题描述】:
用record 尝试一些代码并记录组件。我正在使用可变稀有组件,并在自定义构造函数上遇到编译时错误。
public record Break<R extends Record>(R record, String... notifications) {
public Break(R record, String... notifications) {
System.out.println("record: " + record + " and notifications: " + Arrays.toString(notifications));
this.record = record;
this.notifications = notifications;
}
// compile error: non canonical record constructor must delegate to another costructor
public Break(R record) {
System.out.println("record: " + record);
this.record = record;
}
public Break() {
this(null); // this works
// actually intelliJ suggests it uses the constructor that is not compiling
}
public static void main(String[] args) {
new Break<>(new Break<>());
}
}
我很想了解的是,当通过另一个自定义构造函数调用时,类似的构造函数是如何推断出来的,而没有为初始化提供任何组件。
【问题讨论】:
-
我的理解是非规范构造函数不需要只委托给规范构造函数。 Java 仍然可以解析链并检测循环。因此,假设您的
Break(R record)委托给规范构造函数,调用Break()仍然会成功初始化所有组件。
标签: java arity java-record java-16