我有一堂课,看起来像这样:
@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%确定我理解它的目的。就我而言:
staticConstructor
只能生成带有all参数的静态构造函数。我不想暴露这一点。我真的只想要这两个静态“构造函数”已经在这里了。不,“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);
}
}