Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Record with @Builder.Default

Tags:

java

lombok

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?

like image 892
Bohdan Petrenko Avatar asked Nov 21 '25 21:11

Bohdan Petrenko


2 Answers

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]

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.

like image 40
xthe_white_lionx Avatar answered Nov 23 '25 11:11

xthe_white_lionx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!