简体   繁体   English

为什么不能在Java中序列化Constructors对象?

[英]Why can't Constructors objects be serialized in Java?

I have a class that implements Serializable , it's part of a bigger mesh of objects, it contains a Constructor field, but when it's the Constructors turn to be serialized it throws the NotSerializableException . 我有一个实现Serializable的类,它是更大的对象网格的一部分,它包含一个Constructor字段,但是当转为序列化的Constructor时,它将引发NotSerializableException

I guess I'll have to write the logic myself and recreate the constructor myself every time I deserialize the containing object, but why the heck on earth would the designers of Java wanna create such hassle in the first place? 我想我每次反序列化包含对象时都必须自己编写逻辑并自己重新创建构造函数,但是为什么Java的设计人员首先想创造这样的麻烦呢? I realize that the ClassLoader is needed to figure out the identity of a class, and that the ClassLoader itself will not be serialized and deserialized, but shouldn't the constructor remember the string arguments used to create it? 我意识到需要ClassLoader来确定类的标识,并且ClassLoader本身不会被序列化和反序列化,但是构造函数是否不应该记住用于创建它的字符串参数?

Yes, as you realized Constructor is not serializable. 是的,因为您意识到Constructor不可序列化。

You need to make the Constructor field transient and restore it manually, when needed. 您需要使“ Constructor字段处于瞬态状态,并在需要时手动将其还原。

Yes, the Java designers could have made the Constructor class serialized down to the class name and argument list, but that would open a huge can of worms, basically boiling down to the fact that in any given JVM there can be an arbitrary number of classes with that name and there's no sane way to know which one to use when deserializing such an object. 是的,Java设计人员本可以使Constructor类序列化为类名称和参数列表,但这将打开大量蠕虫,基本上是在任何给定的JVM中可以存在任意数量的类的事实。使用该名称,并且没有一种明智的方法来知道在反序列化此类对象时使用哪个。

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

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