我在学校学习过如何实现 Serialized,但从未提及哪些对象(如果有的话)已经在 Java 中执行此操作。所以我的问题在标题“是否有一些对象或数据类型可以被Java自动序列化(无需实现Serialized)?”如果是的话,它们是什么?其背后的原因是什么?
最佳答案
Javadoc很清楚(重点是我的):
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized.
但要回答:
"Are there some objects or data types that are automatically serialized by Java (without having to implement Serializable)?"
答案是肯定的,如 Javadoc补充说:
All subtypes of a serializable class are themselves serializable.
这是更详细的答案:
1) 基元事实上是可序列化的。
2) 非常重要的一些 JDK 类实现了 Serialized
。这是有道理的,因为这些不能被客户端修改,因此不能被序列化。
Here是javadoc中生成的“接口(interface)java.io.Serialized的使用”。这个列表非常庞大。
3) 每个数组类型都实现接口(interface) Cloneable 和 java.io.Serialized ,其原因与其他 JDK 类完全相同。( JLS 10.1 Array Types) .
4) 可序列化类的所有子类型本身都是可序列化的。
例如,javax.swing.JComponent
是除顶级容器之外的所有 Swing 组件的基类,它实现了 Serialized
:
public abstract class JComponent extends Container implements Serializable,...{...}
因此,它的子类不需要直接实现 Serialized
,而且实际上大多数子类都不需要这样做。
例如:
public abstract class AbstractButton extends JComponent implements ItemSelectable, SwingConstants {...}
public class JButton extends AbstractButton implements Accessible {...}
public class JComboBox<E> extends JComponent{...}
我们可以看到 Number
的类似情况,它是数值的基类。
Number
实现 Serialized
:
public abstract class Number implements java.io.Serializable {...}
许多子类通过传递性实现Serialized
:
public final class Integer extends Number implements Comparable<Integer> {...}
public final class Float extends Number implements Comparable<Float> {...}
但请注意,实现 Serialized
的类的子类也可以显式实现 java.io.Serialized
,例如:
public class AtomicInteger extends Number implements java.io.Serializable {...}
这样做可能是为了使源代码中的信息更加明确。
但如果代码不稳定并且层次结构可能发生变化,它也可能会有所帮助。
无论发生什么变化,该类都会继续可序列化。
关于java - 是否有一些对象或数据类型可以被 Java 自动序列化(无需实现 Serialized)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47911896/