0

通过 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()从它自己的类中调用方法吗?

4

1 回答 1

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

于 2013-06-01T19:45:53.347 回答