有没有办法在构造期间但在构造函数之后执行方法?

Is there a way to execute a method during construction but after the constructor?

我正在使用 lombok 并尽量减少代码。这是我在香草 java:

中的(人为的)情况
public class MyClass {
    private final int x;
    private final int sqrt;
    public MyClass(int x) {
        this.x = x;
        sqrt = (int)Math.sqrt(x);
    }
    // getters, etc
}

但是我想用lombok生成构造函数和getters:

@Getter
@RequiredArgsConstructor
public class MyClass {
    private final int x;
    private int sqrt;
}

要将计算纳入 class,您可以考虑一个实例块:

{
    sqrt = (int)Math.sqrt(x);
}

但是实例块构造函数中的代码执行之前执行,所以x还没有被初始化。

有没有办法执行sqrt = (int)Math.sqrt(x);x被赋值构造函数参数,但仍然使用生成的构造函数通过 RequiredArgsConstructor?

备注:

如何使用 lazy option on @Getter 进行计算:

// tested and works OK
@Getter(lazy = true) 
private final int sqrt = (int) Math.sqrt(x);

注意:调用 getSqrt() 的工作方式与 expected/hoped 相同,触发计算并设置 "final" 字段,但是直接访问该字段不会调用魔法 - 您会得到未初始化的值.