假设我有一个具有给定结构的类:
class Problem {
private String longString;
private String firstHalf;
private String secondHalf;
}
firstHalf 和 secondHalf 是根据 longString 计算的,并在我的应用程序中广泛使用,但我不想序列化它们。现在,为了使该对象能够序列化,我需要一个 longString 的 setter 。我想保护 firstHalf 和 secondHalf 从 longString 计算得出的不变量,仅当 longString 存在并且该值存在时才存在传递给 longString 在某种意义上是正确的,可以计算前半部分和后半部分。我当前的解决方案是将 longString 的 setter 写成这样:
public void setLongString(String value) {
this.longString=value;
this.firstHalf=computeFirstHalf(value);
this.secondHalf=computeSecondHalf(value);
}
此代码还暗示了 longString 与前半部分和后半部分之间的紧密相关性。
然而,让我烦恼的一件事是,该方法 setLongString 实际上做了三件事,而且它的名称并没有反射(reflect)它的真实行为。
有没有更好的方法来编码?
编辑1: 我正在使用 Jackson 到 json 序列化器,并且我有前半部分和后半部分的 setter/getter ,并用 @JsonIgnore 进行注释。
我想表达 longString 与其半部分之间的紧密耦合。
最佳答案
class Problem {
private String longString;
private String firstHalf;
private String secondHalf;
//Getters of All Variables
......
......
......
// Setters of All Variables.
public void setLongString(String longString){
this.longString = longString;
}
// public but no Arguments so that user won't be able to set this Explicitly but
//make a call Outside of the Class to set Only and only if longString is there.
public void setFirstHalf(){
if(this.longString == null)
throw new Exception("Long String is Not Set.");
this.firstHalf = this.computeFirstHalf(this.longString);
}
// public but no Arguments so that user won't be able to Set Explicitly but
//make a call Outside of the Class to set Only and only if longString is there.
public void setSecondHalf(){
if(this.longString == null)
throw new Exception("Long String is Not Set.");
this.secondHalf = this.computeSecondHalf(this.longString);
}
//private method not Accessible outside of Class
private String computeFirstHalf(final String value){
//Your Logical Code.
}
//private method not Accessible outside of Class
private String computeSecondHalf(final String value){
//Your Logical Code.
}
关于java - 使用取决于其他字段的字段序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920385/