I am having two classes: 1]BaseCustomer.java
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder(builderMethodName="BaseBuilder")
public class BaseCusmtomer {
private String cutomerId;
private String age;
@Default
private Boolean isActive= true;
@Default
private String type = "XYZ";
}
2] Customer.java
@Builder
public class Customer extends BaseCustomer{
private Customer(String cutomerId, String age, Boolean isActive, String type){
super(customerId,age,isActive,type);
}
}
3]Test Object
Customer.builder().cutomerId("1").age("23").build();
ut while creating object using Customer builder it always take values of isActive and type as null, it should take default values from superclass. Is there anyway to do this?
Tried to call Child builder with default parent class values but getting null values instead of default value.
Note: can't use Superbuilder as it is experimental feature.
CodePudding user response:
Just remove the @Builder
from the Customer
class and just use @Builder
on BaseCustomer
:
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
public class BaseCustomer {
private String customerId;
private String age;
@Default
private Boolean isActive = true;
@Default
private String type = "XYZ";
}
public class Customer extends BaseCustomer {
}
Note: you don't need to create a constructor on Customer
class.
CodePudding user response:
The problem you're facing is that the @Default annotation is not being used by the Customer class's builder.
One way to solve this issue is to define the fields in the Customer class that correspond to the fields in the BaseCustomer class with default values, and then pass them as arguments to the superclass's constructor.
Here's an example of how you could update your Customer class:
@Builder
public class Customer extends BaseCustomer {
private Customer(String customerId, String age, @Default("true") Boolean isActive, @Default("XYZ") String type) {
super(customerId, age, isActive, type);
}
}
Here, when you build object of Customer by providing only customerId and age, the isActive and type will be passed as default values true and XYZ respectively.
It's worth noting that you should also add the same default values in the @Builder method of the class, something like this:
@Builder(builderMethodName = "CusBuilder", defaultValue = "XYZ", defaultBoolean = true)
this way when you use CusBuilder() instead of builder() you'll get the default values.
Additionally, If you are not using Superbuilder, it's important to document the expected behavior of the @Default annotations in your codebase, so that other developers can understand how they're supposed to be used.