在ObjectOutputStream上发送自制对象时,该对象的服务器和客户端类是否必须相同?
例如,当一些Action只能在服务器上执行时,因为它只需要服务器上的其他几个类,客户端上的类可以与服务器上的类不同吗?
服务器类:
public class SomeAction implements Action, Serializable {
private static final long serialVersionUID = 1L; //Just some serialVersionUID
private String name;
public SomeAction(String name) {
//This property must be sent to the server
this.name = name;
}
@Override
public void performAction() {
System.out.println("New client connected");
Server.getConnections().add(1); //Increases the number of connections on the server. Of course, this is only available on the server.
//Do something with the client
. . .
}
}
客户端类:
public class SomeAction implements Action, Serializable {
private static final long serialVersionUID = 1L; //Just some serialVersionUID
private String name;
public SomeAction(String name) {
//This property must be sent to the server
this.name = name;
}
@Override
public void performAction() {
System.out.println("New client connected");
//The getConnections().add(1) wont work on the client.
//Do something with the client
. . .
}
}
现在客户端可以将其类发送到服务器,然后服务器是否会从自己的类中调用performAction()
方法?
答案 0 :(得分:1)
课程可以有所不同,但不会有太多不同。关于这些类之间的“兼容性”,有几条规则。
见
http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serialTOC.html
例如,可以向类中添加新方法,并将serialVersionUID字段保持为相同的值,并且不要使用新方法 - 当然,这不会打扰。
更新
更好的链接:
http://web.archive.org/web/20051125013312/http://www.macchiato.com/columns/Durable4.html