Java:如何使这个Serializable?

我需要以下类是Serializable。

package helpers; public class XY implements Comparable { public int x; public int y; public XY (int x, int y) { this.x = x; this.y = y; } public int compareTo( XY other ) { String compare1 = this.x + "-" + this.y; String compare2 = other.x + "-" + other.y; return compare1.compareTo( compare2 ); } public String toString() { return this.x + "-" + this.y; } } 

截至目前,我不能将它作为一个带有outputstream的对象发送。我试图实现Serializable,但这不起作用。

实现Serializable 起到作用,但您必须使用ObjectOutputStream编写对象,而不仅仅是OutputStream。

你只需要从java.io.Serializableinheritance:

public class XY implements Comparable, java.io.Serializable

在此查看有关序列化的更多信息

请参阅Apache Commons Lang提供的SerializationUtils API 。

这样更安全,更易于维护。 🙂