'The Function implementation remains null if Lombok @Builder is used for initialization
I am using Lombok to initialize a class. That class also has some Functions defined. Those Functions remain null when called from the above initialized object.
VehicleTest Class:
public class VehicleTest {
public static void main(String...arg) {
Vehicle vehicle = Vehicle.builder()
.createdDateTime(DateUtil.getEpochTimeFromCurrentTimeZone())
.make("Toyota")
.year("2010")
.model("Fortunner")
.build();
System.out.println(vehicle.convertEpochToString.apply(DateUtil.getEpochTimeFromCurrentTimeZone()));
}
}
Vehicle Class:
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Vehicle {
Long createdDateTime;
String year;
String make;
String model;
public String getTime() {
return convertEpochToString.apply(createdDateTime);
}
public Function<Long,String> convertEpochToString = epochTime -> {
ZonedDateTime zonedDateTime = DateUtil.convertEpochToZonedDateTime(epochTime);
return DateUtil.formatZonedDateTime(zonedDateTime,"dd-MMM-yyyy");
};
}
As you can see in this debug mode, this convertEpochToString Function is null.
Note: This is not the actual way I am using in my project. This is just an example I made to depict my problem.
As mentioned in this link, if I use
@Builder.Default
on above Function, this seems to be working. But adding it on all 100+ Functions in each class will be a huge task for me. Is there any other alternative apart from the above one and static Function?
Solution 1:[1]
You can solve this case by adding modifier static to the function declaration.
But I'm not sure about the reasons for such behavior, I think Lombok code generation can make decisions if works with class and can't if works with instance of class and lazy function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dmitrii B |

