反序列化对象时忽略字段,以避免ClassCastException

时间:2019-07-09 10:54:31

标签: java serialization

我有一个序列化的对象,想使用ObjectInputStream反序列化它。不幸的是,该类包含一些无法反序列化的字段,因为它们是lambda,并且在反序列化时我在classpath上没有适当的类文件。

我正在尝试从对象中提取信息,我对那些lambda字段不感兴趣,但是对其他一些可以反序列化的字段不感兴趣(我可以在通过ObjectInputStream.readObject进行调试时看到这一点)

请注意,我对序列化的类(第三方库)没有任何控制权,因此无法使用瞬态或任何其他机制来更改类。我也不能更改序列化过程。我所拥有的只是作为字符串表示形式的序列化对象,我必须使用它。

示例:


public interface SomeInterface {

  public String doSomething();

}

public class Information {

  private String informationIWantToRead;
  private SomeInterface someLambdaIDontCareAbout;

}

public class App {
  public static void main(String[] args) {
    Information information = new Information();
    information.setInformationIWantToRead("i want this");
    information.setSomeLambdaIDontCareAbout(() -> "dont care about this");

    // use ObjectOutputStream to serialize information object and encode as string

  }
} 

...

public class AppInOtherVM {
  public static void main(String[] args) {

    // another VM: decode string and deserialize information object using ObjectInputStream 

  }
} 

当我使用ObjectInputStream.readObject()反序列化对象(并且App.class不在类路径中并且不再可用)时,抛出ClassCastException:

java.lang.ClassCastException:无法在Information实例中将java.lang.invoke.SerializedLambda的实例分配给SomeInterface类型的字段Information.someLambdaIDontCareAbout

是否有任何方法(使用自定义ObjectInputStream?)反序列化此对象并忽略无法反序列化的字段?当someLambdaIDontCareAbout为null时,我将非常高兴。

0 个答案:

没有答案