如果对象在序列化之前被向上转换,那么序列化在 Java 中如何工作?

发布于 2024-12-11 19:45:29 字数 683 浏览 0 评论 0原文

假设我有一个接口和一个对象:

public interface MyInterface {
    public String getStringOne();
}

public class MyObject implements MyInterface {
    private final String stringOne = "string1";
    private final Image myGiganticImage; // loads from disk in the constructor

    // Getters for both would follow
}

如果我在通过网络发送之前将 MyObject 向上转换为 MyInterface,那么会传输什么?

public class MyService {
    private final MyObject data = new MyObject();

    public MyInterface getData() {
        return data;
    }
}

具体来说,myGiganticImage 是否通过线路发送?

Say I have an interface and an object:

public interface MyInterface {
    public String getStringOne();
}

public class MyObject implements MyInterface {
    private final String stringOne = "string1";
    private final Image myGiganticImage; // loads from disk in the constructor

    // Getters for both would follow
}

What gets transferred if I upcast MyObject to MyInterface before sending it across the wire?

public class MyService {
    private final MyObject data = new MyObject();

    public MyInterface getData() {
        return data;
    }
}

Specifically, does myGiganticImage get sent across the wire?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

找个人就嫁了吧 2024-12-18 19:45:29

显然,MyObject 的状态是序列化的。 public MyInterface getData() 只是强制 getData() 返回的类型是 MyInterface

Obviously the state of MyObject is serialized. public MyInterface getData() just enforces that the type returned by getData() is-a MyInterface.

爱,才寂寞 2024-12-18 19:45:29

向上转换不会更改对象的内容。

Upcasting doesn't change the content of the object.

┈┾☆殇 2024-12-18 19:45:29

向上转换只是更改指针类型的一种方法。无论指针类型如何,JVM 堆上都会保留相同的数据结构。这个结构实际上并不关心你指向它的方式。

当您序列化对象时,系统(可能)会向您的对象询问类(getClass()),然后使用反射读取此类中的所有字段。
即使您使用Object指向它,对象也始终会报告其类。

系统将始终从类中读取字段,因为这是 java 中获取字段列表的唯一方法:向对象询问类,然后向类询问字段。

如果您想转移对象的父级,您可以尝试我的解决方案: 将远程对象反序列化为最窄的可访问类

Upcasting is just a way to change pointer type. The same data structure kept on your JVM heap regardless pointer type. This structure really does not care about the way you point to it.

When you serialize object system (probably) would ask your object for class (getClass()) and then read all fields from this class using reflection.
Object would always report its class even if you point to it using Object.

System will always read fields from class because it is the only way in java to get list of fields: ask object for class and than ask class for fields.

If you want to transfer object's parent you may try my solution: Deserialize remote object to the narrowest accessible class

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文