2

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?

enter image description here

Ahamed Abdul Rahman
  • 512
  • 1
  • 5
  • 18
  • Make them `static final`, which is better anyway, because it seems they are not intended to be used as a real instance variable. – Jan Rieke Feb 24 '22 at 18:44

2 Answers2

0

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.

Dmitrii B
  • 2,672
  • 3
  • 5
  • 14
0

Solved this problem with

@Builder(toBuilder = true)

and modifying the initialization from

Vehicle vehicle = Vehicle.builder()

to

Vehicle vehicle = new Vehicle().toBuilder()

This seems to be quite easy for me.

Read it from here

Ahamed Abdul Rahman
  • 512
  • 1
  • 5
  • 18