【问题标题】:Immutables custom create and of methods不可变的自定义创建和方法
【发布时间】:2022-10-24 20:43:22
【问题描述】:
我正在更改使用Immutables 的库。
在我更改的类中,我刚刚添加了一个新变量,在生成的类中,我在 create 和 of 方法中看到了不同的签名。
ImmutableMyClass.of(previous variables ..., int varNew)
ModifiableMyClass.create(previous variables ..., int varNew)
由于这个库的用户调用了这些方法的早期版本,我需要保留以前的版本,同时为新功能提供新版本;否则,显然,我正在破坏向后兼容性。
如何让 Immutables 创建自定义 create 和 of 方法?
【问题讨论】:
标签:
java
reflection
immutability
immutables-library
【解决方案1】:
您只需按照此处库文档中的定义自行添加缺少的方法:https://immutables.github.io/immutable.html#expressive-factory-methods。因此,对于缺少的方法,您定义 public static MyClass of(...) 和 public static MyClass create(...) 方法如下
@Value.Modifiable
@Value.Immutable
public abstract class Point {
@Value.Parameter
public abstract double x();
@Value.Parameter
public abstract double y();
//You added this for example
@Value.Parameter
public abstract double z();
public static Point origin() {
return ImmutablePoint.of(0, 0);
}
public static MyClass of(double x, double y) {
return ImmutableMyClass.of(x, y, 0); // or another implementation you need
}
public static MyClass create(double x, double y) {
return ModifiableMyClass.create(x, y, 0); // or another implementation you need
}
}