Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

1. Introduction

Lombok is a library that helps us significantly reduce boilerplate code when writing Java applications.

In this tutorial, we'll see how we can make copies of immutable objects with changes to only a single property using this library.

2. Usage

When working with immutable objects, which by design don't allow setters, we may need a similar object to the current one, but with only one property different. This can be achieved using Lombok's @With annotation:

public class User {
    private final String username;
    private final String emailAddress;
    @With
    private final boolean isAuthenticated;

    //getters, constructors
}

The above annotation generates the following under the hood:

public class User {
    private final String username;
    private final String emailAddress;
    private final boolean isAuthenticated;

    //getters, constructors

    public User withAuthenticated(boolean isAuthenticated) {
        return this.isAuthenticated == isAuthenticated ? this : new User(this.username, this.emailAddress, isAuthenticated);
    }
}

We can then use the above-generated method to create mutated copies of the original object:

User immutableUser = new User("testuser", "[email protected]", false);
User authenticatedUser = immutableUser.withAuthenticated(true);

assertNotSame(immutableUser, authenticatedUser);
assertFalse(immutableUser.isAuthenticated());
assertTrue(authenticatedUser.isAuthenticated());

Additionally, we have the option of annotating the whole class, which will generate withX() methods for all the properties.

3. Requirements

To use the @With annotation correctly, we need to provide an all-arguments constructor. As we can see from the above example, the generated method requires this to create a clone of the original object.

We can use either Lombok's own @AllArgsConstructor or @Value annotation to satisfy this requirement. Alternatively, we can manually provide this constructor as well while ensuring that the order of the non-static properties in the class matches that of the constructor.

We should remember that the @With annotation does nothing if used on static fields. This is because static properties are not considered part of an object's state. Also, Lombok skips the method generation for fields that start with the $ sign.

4. Advanced Usage

Let's investigate some advanced scenarios when using this annotation.

4.1. Abstract Classes

We can use the @With annotation on a field of an abstract class:

public abstract class Device {
    private final String serial;
    @With
    private final boolean isInspected;

    //getters, constructor
}

However, we will need to provide an implementation for the generated withInspected() method. This is because Lombok will have no idea about the concrete implementations of our abstract class to create clones of it:

public class KioskDevice extends Device {

    @Override
    public Device withInspected(boolean isInspected) {
        return new KioskDevice(getSerial(), isInspected);
    }

    //getters, constructor
}

4.2. Naming Conventions

As we identified above, Lombok will skip fields that start with the $ sign. However, if the field starts with a character, then it is title-cased, and finally, with is prefixed to the generated method.

Alternatively, if the field starts with an underscore, then with is simply prefixed to the generated method:

public class Holder {
    @With
    private String variableA;
    @With
    private String _variableB;
    @With
    private String $variableC;

    //getters, constructor excluding $variableC
}

According to the above code, we see that only the first two variables will have withX() methods generated for them:

Holder value = new Holder("a", "b");

Holder valueModifiedA = value.withVariableA("mod-a");
Holder valueModifiedB = value.with_variableB("mod-b");
// Holder valueModifiedC = value.with$VariableC("mod-c"); not possible

4.3. Exceptions to Method Generation

We should be mindful that in addition to fields that start with the $ sign, Lombok will not generate a withX() method if it already exists in our class:

public class Stock {
    @With
    private String sku;
    @With
    private int stockCount;

    //prevents another withSku() method from being generated
    public Stock withSku(String sku) {
        return new Stock("mod-" + sku, stockCount);
    }

    //constructor
}

In the above scenario, no new withSku() method will be generated.

Additionally, Lombok skips method generation in the following scenario:

public class Stock {
    @With
    private String sku;
    private int stockCount;

    //also prevents another withSku() method from being generated
    public Stock withSKU(String... sku) {
        return sku == null || sku.length == 0 ?
          new Stock("unknown", stockCount) :
          new Stock("mod-" + sku[0], stockCount);
    }

    //constructor
}

We can notice the different naming of the withSKU() method above.

Basically, Lombok will skip method generation if:

  • The same method exists as the generated method name (ignoring case)
  • The existing method has the same number of arguments as the generated method (including var-args)

4.4. Null Validations on Generated Methods

Similar to other Lombok annotations, we can include null checks to the methods generated using the @With annotation:

@With
@AllArgsConstructor
public class ImprovedUser {
    @NonNull
    private final String username;
    @NonNull
    private final String emailAddress;
}

Lombok will generate the following code for us along with the required null checks:

public ImprovedUser withUsername(@NonNull String username) {
    if (username == null) {
        throw new NullPointerException("username is marked non-null but is null");
    } else {
        return this.username == username ? this : new ImprovedUser(username, this.emailAddress);
    }
}

public ImprovedUser withEmailAddress(@NonNull String emailAddress) {
    if (emailAddress == null) {
        throw new NullPointerException("emailAddress is marked non-null but is null");
    } else {
        return this.emailAddress == emailAddress ? this : new ImprovedUser(this.username, emailAddress);
    }
}

5. Conclusion

In this article, we have seen how to use Lombok's @With annotations to generate clones of a particular object with a change in a single field.

We also learned how and when this method generation actually works, along with how to augment it with additional validations such as null checks.

As always, the code examples are available over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Generic footer banner
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!