lombok的“staticConstructor”适用于这种情况吗?

问题描述 投票:0回答:1

我有一堂课,看起来像这样:

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@Getter
public class MyClass {

    Integer mField1;
    String mField2;

    // No public constructor. You may NOT call (null, null) or (field1, field2)

    // Factory-like constructor, when there's only field1
    public static MyClass fromField1(@NotNull final Integer field1) {
        return new MyClass(field1, null);
    }

    // Factory-like constructor, when there's only field2
    public static MyClass fromField2(@NotNull final String field2) {
        return new MyClass(null, field2);
    }
}

我可以更换这个吗:

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@Getter

...有了这个:

@Value(...)

...如果是,怎么办?

我猜测

staticConstructor
与此用例相关,但我不能 100% 确定它符合需求。就我而言:

  1. 当有多个类似静态构造函数的方法时,我不知道该怎么办。
  2. 我有一种感觉,
    staticConstructor
    只能生成带有all参数的静态构造函数。我不想暴露这一点。我真的想要这两个静态“构造函数”已经在这里了。
java lombok
1个回答
1
投票

不,“staticConstructor”不适用于这种情况。

目标是用伪 Vanilla Java 生成它:

class MyClass {
   private MyClass(param1, param2) {} // <-- PRIVATE

   // absolutely no way of having both values null or both not null.
   public static MyClass ofParam1(param1) { return new MyClass(param1, null); }
   public static MyClass ofParam2(param2) { return new MyClass(null, param2); }
}

如果我这样做:

@Value(staticConstructor = "of")

然后我明白了

class MyClass {
   private MyClass(param1, param2) {}

   // I don't want this method
   public static MyClass of(param1, param2) { return new MyClass(param1, param2); }
   
   public static MyClass ofParam1(param1) { return new MyClass(param1, null); }
   public static MyClass ofParam2(param2) { return new MyClass(null, param2); }
}

如果我这样做:

@Value(staticConstructor = "ofParam1")

然后我明白了

class MyClass {
   private MyClass(param1, param2) {}

   // I don't want this method
   public static MyClass ofParam1(param1, param2) { return new MyClass(param1, param2); }
   
   public static MyClass ofParam1(param1) { return new MyClass(param1, null); }
   public static MyClass ofParam2(param2) { return new MyClass(null, param2); }
}

我能做的就是这样:

@Value
@AllArgsConstructor(access = AccessLevel.PRIVATE)

总而言之,最好的代码缩减就是用@Value替换@FieldDefaults+@Getter:

(使用问题中的代码)

@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Value
public class MyClass {

    Integer mField1;
    String mField2;

    // No public constructor. You may NOT call (null, null) or (field1, field2)

    // Factory-like constructor, when there's only field1
    public static MyClass fromField1(@NotNull final Integer field1) {
        return new MyClass(field1, null);
    }

    // Factory-like constructor, when there's only field2
    public static MyClass fromField2(@NotNull final String field2) {
        return new MyClass(null, field2);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.