How to Exclude Property from Lombok Builder

How to exclude property from Lombok builder?

Yes, you can place @Builder on a constructor or static (factory) method, containing just the fields you want.

Disclosure: I am a Lombok developer.

How can I exclude a property from a lombok builder only if the property is null

Add following annotation if you want to exclude during serialization:

@JsonInclude(Include.NON_NULL)

Lombok builder - ignore objects with null value

There are multiple things to mention:

  1. you can filter the cars before the convertion
externalCars.stream()
.filter(car -> Objects.nonNull() && isCarValid())
.map(CarConverter::convertToCar)
.collect(Collectors.toSet())

  1. you can do some checks within your conversion method and filter afterwards
public class CarConverter {

private Car convertToCar(ExternalVehicles vehicles) {
if (vehicles == null || getPlateNumberFromObjectNestedInExternalVehicles("plateNumber") == null)
return null

return Car.builder()
.plateNumber(getPlateNumberFromObjectNestedInExternalVehicles("plateNumber"))
.brand(getBrandFromObjectNestedInExternalVehicles("brand"))
.build();
}
}

and then filter before the collection

externalCars.stream()
.map(CarConverter::convertToCar)
.filter(car -> Objects.nonNull())
.collect(Collectors.toSet())

In my experience, this leads to less NullPointerExceptions

Just for completion, there are also way,to fail the .build() method as seen here:
https://stackoverflow.com/a/72654258/1538176

Is there a way to exclude all the fields from @EqualsAndHashCode other than the @Id column

Use @EqualsAndHashCode(onlyExplicitlyIncluded = true) on the class and then @EqualsAndHashCode.Include on the field to include.

Override lombok builder and change value type

First we run delombok to get a better idea of what's happening, and then compile the output.

java -jar lombok.jar delombok -p Foo.java >Foo2.java
# Rename Foo2.java or make the `class Foo` declaration non-public
javac Foo2.java

gets us:

Foo2.java:63: error: incompatible types: List<BarEnum> cannot be converted to List<String>
return new Foo.FooBuilder().barList(this.barList).number(this.number);
^

And then the answer is clear: Lombok needs the barList(List<BarEnum>) variant of the builder barList method to exist. By writing it yourself, lombok doesn't generate its own version.

Lombok core developer speaking here: We don't, because it is quite difficult to ascertain if there is a signature clash. Thus, we notice a method with the same name as something we want to generate and with the same argument count, and we don't do any further analysis: That's a 'match' and means lombok doesn't generate this method anymore, assuming that you've taken over the responsibility for it. This is a fine, fine example: There cannot be a barList(List<BarEnum>) method in addition to your explicit barList(List<String>) method because you can't have 2 methods that differ solely in the generics parts of the arguments! (Try it - won't compile).

Thus, your approach here is fundamentally untenable. The fix is fairly easy - make that custom method something like:

public FooBuilder barStringList(List<String> barStringList) { .. }

i.e. give it another name. Now lombok will also generate barList(List<BarEnum>) and all will be well.

If you want the barlist(List<BarEnum>) variant to not exist, then don't, but you'll have to handwrite the toBuilder() part of it: At that point it is no longer possible for lombok to automatically know how to turn an instance into a pre-filled builder anymore, if you start just effectively removing the very methods that are needed as 'setters' to make that work.

DISCLAIMER: I'm a core lombok dev.

Keep original lombok builder setter and overload

You can make Lombok ignore existing methods by annotating them with @Tolerate.

Java Lombok: Omitting one field in @AllArgsConstructor?

No that is not possible. There is a feature request to create a @SomeArgsConstructor where you can specify a list of involved fields.

Full disclosure: I am one of the core Project Lombok developers.

How to update any parameter value of existing java lombok Builder object?

When you call toBuilder.age(40).build() you are not reassigning that to the instance.
The code should look like this:

a = a.toBuilder().age(40).build();

Let me know if it has been helpful.

@Builder Lombok - Inheritance

You cannot cast an instance of BaseClassBuilder to UserWithNameBuilder, because the inheritance relation is in the opposite direction, as it reflects the relation between the annotated classes: UserWithNameBuilder extends BaseClassBuilder, like UserWithName extends BaseClass.

Thus, there is no way around calling the builder() method of the very class you want to build.

That being said, I guess that the primary purpose of your generateBaseBuilder() method is not to create the builder, but to set some default values for the new instances. There are two ways to achieve this:

  1. Add default values (as field initializers) to your fields and put a @Builder.Default on them.

  2. Rewrite your generateBaseBuilder method to become setDefaultValues that takes a builder instance as parameter and only sets those values:

public static <T extends BaseClass.BaseClassBuilder<?, ?>> T setDefaultValues(T builder) {
builder
.userID("1")
.clientID("1");
return builder;
}

public static UserWithName generateUserWithName(String name) {
UserWithNameBuilder<?,?> builder = setDefaultValues(UserWithName.builder());
return builder
.name(name)
.build();
}

I'd prefer the first option because it is more concise. However, the second option is more flexible, as you can have multiple of those setValues methods, each of which could set different values.

Note that you could also include this/these method(s) directly into the BaseClassBuilder. There are a few questions and answers here at StackOverflow that discuss customizing @SuperBuilder.



Related Topics



Leave a reply



Submit