简体   繁体   English

如果包含“对象”字段,如何使类可序列化

[英]How to make a class serializable if it include a field of “Object”

public class A implements Serializable
{
    private static final long serialVersionUID = 1L;
    private Object value;
    private Type type;
....
}

It includes "Object" which is not serializable, so class A will be rendered as not serializable. 它包含不可序列化的“对象”,因此类A将呈现为不可序列化。

"Object value" could be Integer, String..., depending on "Type type" “对象值”可以是Integer,String ...,具体取决于“类型类型”

How to make A serializable? 如何制作A序列化? Thanks in advance! 提前致谢!

EDIT: Will "Object value" get lost (when de-serialing) if using "private transient Object value"? 编辑:如果使用“私有瞬态对象值”,“对象值”是否会丢失(当解除序列时)? I don't want to lost it. 我不想失去它。

Is there a general serializable Object type? 是否有一般的可序列化对象类型?

"Object value" could be Integer, String... “对象值”可以是整数,字符串......

Integer and String are both serializable. Integer和String都是可序列化的。 It will work. 它会工作。 You don't need to do anything special to serialize them. 您无需执行任何特殊操作来序列化它们。

Is there a general serializable Object type? 是否有一般的可序列化对象类型?

Yeah, Serializable: 是的,可序列化:

private Serializable value;

您可以使用transient关键字跳过字段的序列化:

private transient Object value;

transient keyword servers that purpose transient关键字服务器的目的

private transient Object value;

Other way is to make the Object static if it does not represent your instance. 其他方法是,如果Object不代表您的实例,则使其为静态。 static variables are implicitly transient . 静态变量是隐式transient

Will "Object value" get lost (when de-serialing) if using "private transient Object value"? 如果使用“私有瞬态对象值”,“对象值”是否会丢失(当解除序列化时)? I don't want to lost it. 我不想失去它。

If you do not serialize the variable its values will be lost. 如果不序列化变量,则其值将丢失。 Serialization saves the state of instance of a class. 序列化保存了类的实例状态。 When the instance will be deserialized it will have Object value in it but it will be initialized to the default value ie null. 当实例将被反序列化时,它将具有Object值,但它将被初始化为默认值ie null。 So yes the value will be lost which is anyway the purpose of making a variable transient. 所以是的,价值将会失去,无论如何,这是一个变量瞬态的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM