如何序列化 Java 中的 AttributedString?

How can I serialize an AttributedString in Java?

或者以其他方式保存它。 我尝试创建一个 class,它继承自 AttributedString 并实现了 Serializable,但没有成功。

https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html 声明如下:

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

AttributedString 没有可供扩展子类访问的无参数构造函数,因此反序列化将失败。

如您所见,AttributedString class 未实现 Serializable 且未提供无参数构造函数。因此序列化失败。 AFAIK,Java SE 库中没有任何东西可以(直接)处理这个问题。

但是,我找到了一个名为 org.jfree.io.SerialUtilities 的带有 class 的第 3 方库,它提供了通过 ObjectOutputStream 和 [=15] 序列化和反序列化 AttributedString 对象的方法=].

要使用这些方法,您通常需要为使用这些类型的任何可序列化 class 编写自定义 readObjectwriteObject 方法。我在这里找到了一些例子: