为什么 Java 需要 Serializable 接口? [英] Why Java needs Serializable interface?

查看:34
本文介绍了为什么 Java 需要 Serializable 接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在序列化方面做了大量工作,必须在我们使用的每个对象上指定 Serializable 标签是一种负担.尤其是当它是一个我们无法真正改变的 3rd 方类时.

We work heavily with serialization and having to specify Serializable tag on every object we use is kind of a burden. Especially when it's a 3rd-party class that we can't really change.

问题是:既然 Serializable 是一个空接口,而一旦你添加了 implements Serializable,Java 就提供了强大的序列化 - 为什么他们不让所有东西都可序列化,仅此而已?

The question is: since Serializable is an empty interface and Java provides robust serialization once you add implements Serializable - why didn't they make everything serializable and that's it?

我错过了什么?

推荐答案

序列化充满了陷阱.这种形式的自动序列化支持使类内部成为公共 API 的一部分(这就是 javadoc 为您提供 类的持久形式).

Serialization is fraught with pitfalls. Automatic serialization support of this form makes the class internals part of the public API (which is why javadoc gives you the persisted forms of classes).

为了长期持久化,类必须能够解码这种形式,这限制了您可以对类设计进行的更改.这打破了封装.

For long-term persistence, the class must be able to decode this form, which restricts the changes you can make to class design. This breaks encapsulation.

序列化也会导致安全问题.通过能够序列化它所引用的任何对象,类可以访问它通常无法访问的数据(通过解析结果字节数据).

Serialization can also lead to security problems. By being able to serialize any object it has a reference to, a class can access data it would not normally be able to (by parsing the resultant byte data).

还有其他问题,例如内部类的序列化形式没有很好地定义.

There are other issues, such as the serialized form of inner classes not being well defined.

使所有类都可序列化会加剧这些问题.查看Effective Java Second Edition,尤其是Item 74:Implement Serializable.

Making all classes serializable would exacerbate these problems. Check out Effective Java Second Edition, in particular Item 74: Implement Serializable judiciously.

这篇关于为什么 Java 需要 Serializable 接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆