【问题标题】:Different Objects in ObjectOutputStreamObjectOutputStream 中的不同对象
【发布时间】:2013-06-02 20:34:37
【问题描述】:

当通过 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()方法吗?

【问题讨论】:

    标签: java java-io objectoutputstream


    【解决方案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

    【讨论】:

    • 因此,只要它们至少具有所有标准方法(例如,所有从 Action 继承)和所有标准字段,那么这些方法或类中的附加方法/字段内部可能存在差异,我说的对吗?
    • a) 方法中的内容对于所有这些兼容性都无关紧要 - 如果您的 Java 程序在服务器上运行,JVM 将使用服务器上的类文件,并且确实不关心或检查方法的内容是否与客户端或其他任何地方的内容不同。
    • b) 如果你例如删除一个方法(在某处使用),这当然是一个问题。据我所知,添加新方法应该不错。重命名是个坏主意,就像删除一样。终于找到了一个不错的链接:web.archive.org/web/20051125013312/http://www.macchiato.com/…
    • 他们写例如:以下是一些你不能不做的事情:更改超类删除字段更改字段名称将字段更改为静态(从非静态)将字段更改为瞬态(从非瞬态)将原始字段的类型更改为其他任何类型(例如字节到短)将非原始字段的类型更改为原始字段(例如字符到字符)
    猜你喜欢
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2019-08-15
    • 2010-09-13
    • 2016-08-01
    相关资源
    最近更新 更多