使用 @Builder.default的Java记录
我想知道有什么方法可以将Java记录与Lombok的@builder.default
相结合? 让我们考虑一个具有新文件创建的属性对象的示例。
在Java 14
@Value
@Builder
public class FileProperties {
@Builder.Default
String directory = System.getProperty("user.home");
@Builder.Default
String name = "New file";
@Builder.Default
String extension = ".txt";
}
Java 14
@Builder
public record FileProperties (
String directory,
String name,
String extension
) {}
之前,但是如果我尝试使用诸如
@Builder
public record FileProperties (
@Builder.Default
String directory = System.getProperty("user.home")
) {}
编译器之类的内容,则会出错,揭示不允许使用这种语法。我们对这个问题有任何解决方案吗?
I'm wondering is there any way to combine java record with lombok's @Builder.Default
?
Let's consider an example with properties object for new file creation.
Before java 14
@Value
@Builder
public class FileProperties {
@Builder.Default
String directory = System.getProperty("user.home");
@Builder.Default
String name = "New file";
@Builder.Default
String extension = ".txt";
}
Java 14
@Builder
public record FileProperties (
String directory,
String name,
String extension
) {}
But in case if I try to use something like
@Builder
public record FileProperties (
@Builder.Default
String directory = System.getProperty("user.home")
) {}
Compiler will fail with an error, revealing that such syntax is not allowed. Do we have any solution to this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过
@builder.default
来实现相同的
结果
You can achieve the same outcome not by
@Builder.Default
but by defining the builder itself with defaults for Lombok:Then to test it:
Output:
此功能目前尚不可用。根据伦波克作者Reinier Zwitserloot的问题的第一个评论:
赖尼尔继续解释了为什么在伦波克实施这会有问题:
This functionality is not available at the moment. Per the first comment under the question by Lombok author Reinier Zwitserloot:
Reinier goes on to explain why this would be problematic to implement in Lombok:
如果您想做更多的事情,请不要使用记录,而不是在容器中记录值。在这种情况下,您不应该使用记录,因为它不允许您指导与简单录制参数不同的东西。
如果您要为任何实例创建此类默认值,则需要一个“正常”的构造函数。
这就是为什么您无法在记录中(再次)设置值的原因。
Don't use a record if you want to do more things than recording values in a container. In this case you shouldn't use a record because it doesn't allow you to instruct something different than simple recording your arguments.
If you want a default value for any instance you are creating of this class you need a "normal" constructor.
That's why you can't set values (again) in records.