使用取决于其他字段的字段序列化对象

Serializing object with fields depending on other field

假设我有一个具有给定结构的 class:

class Problem {
  private String longString;
  private String firstHalf;
  private String secondHalf;
}

firstHalfsecondHalf 是从 longString 计算出来的,在我的应用程序中被广泛使用,但是我不想序列化它们。现在,为了使该对象的序列化工作,我需要 longString 的 setter。我想保护 firstHalfsecondHalflongString 计算的不变量,仅在 [=26] 时存在=]longString 存在并且传递给 longString 的值在某种意义上是正确的,因为可以计算前半部分和后半部分。我目前的解决方案是让 longString 的 setter 写成这样:

public void setLongString(String value) {
  this.longString=value;
  this.firstHalf=computeFirstHalf(value);
  this.secondHalf=computeSecondHalf(value);
}

此代码还暗示 longString 与前半部分和后半部分之间存在紧密关联。

然而,让我感到困扰的一件事是,setLongString 方法实际上做了三件事,它的名称并没有反映它的真实行为。

有没有更好的编码方式?

编辑 1: 我正在使用 Jackson 来 json 序列化器,我有上半场和下半场的吸气剂,用@JsonIgnore 注释。

我想表达 longString 和它的一半之间的紧密耦合。

firstHalf 和 secondHalf 计算可以延迟完成(即使用 getter)

public void getFirstHalf() {
    if (this.longString != null) {
        this.firstHalf = computeFirstHalf(longString);
    }
    return this.firstHalf;
}

下半场同样如此。

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.
}