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?
You can achieve the same outcome not by @Builder.Default
but by defining the builder itself with defaults for Lombok:
@Builder
public record FileProperties (
String directory,
String name,
String extension
) {
public static class FilePropertiesBuilder {
FilePropertiesBuilder() {
directory = System.getProperty("user.home");
name = "New file";
extension = ".txt";
}
}
}
Then to test it:
public static void main(String[] args) {
System.out.println(FileProperties.builder().build());
}
Output:
FileProperties[directory=/home/me, name=New file, extension=.txt]