Skip to content
Advertisement

Why any initialization or even print inside the constructor with @Tolerate lombok cannot be reached?

what is the problem with the constructor with @Tolerate of lombok, and why it cannot be reached? and how can I fix it? I wanna initialize a map by setting some default keys and values inside the constructor block, but it cannot be initialize because nothing can be reached inside the constructor. Would you please help me? thank you.

import java.util.HashMap;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Tolerate;
import lombok.ToString;

@Data
@ToString(includeFieldNames = true)
@Builder
public class A {

    @Builder.Default private HashMap<Integer, Double> map = new HashMap<>();

   @Tolerate
   public A() {
  //          System.out.println("Print to Test 1: ");
      super();
    
    //INTIALIZING MAP WITH DEFAULT VALUE AND KEY
    System.out.println("Print to Test 2: ");
    map.put(47, 0.8);
    map.put(87, 0.9);
    System.out.println("Print to Test 3: ");
    
  }


    public double getValue(int x, int key) {
  
      System.out.println("test 1: " + map); 

      return x * map.get(key);
  }
}

OUTPUT:

test 1: {}

Advertisement

Answer

@Builder does not use a no-args constructor, it uses an all-args constructor. If you want your builder to use your own constructor, manually implement an all-args constructor, but do not annotate it with @Tolerate (otherwise Lombok would try to generate another, which will lead to a compilation error).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement