stackoverflow(翻译Serializable)

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.

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?

What am I missing?

share edit
 
 
What if you want to make your own object Serializable? Or did I misunderstand something? –  Joe Philllips Jan 13 '09 at 22:57
 
I will still get NotSerializableException because all fields of my objects have to be serializable –  Yoni Roit Jan 13 '09 at 23:01

12 Answers

up vote 79 down vote accepted

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.

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

share edit
 
2 
This is clearly the better answer, I am disappointed that the selected answer is not this, it seems the posted chose with a "Im annoyed because I have to declare things serializable" agenda in mind. Its an example of some one wanting to free whell and not heed the security and design lessons that have already been learned in the past. –  gbtimmon Jul 9 '12 at 17:30
 
@McDowell what do you mean by persisted form of classes ? I followed that link but can't understand what you mean ? can you explain this please ? –  Geek Aug 22 '12 at 7:36
 
@Geek - The serialized form of the URL type (for example) defines what private fields the type must have and what order they must be declared in. –  McDowell Aug 22 '12 at 8:05
 
@McDowell Why does the order matter ? –  Geek Aug 22 '12 at 8:15
7 
@McDowell Hi. I'm the original poster of this question from 4 years ago, and I've just selected your answer as accepted, if it means anything. I think your answer is really the better one, and I was probably too immature to see it that way at the time. Fixing now :) –  Yoni Roit Mar 6 '13 at 19:55

I think both Java and .Net people got it wrong this time around, would have been better to make everything serializable by default and only need to mark those classes that can't be safely serialized instead.

For example in Smalltalk (a language created in 70s) every object is serializable by default. I have no idea why this is not the case in Java, considering the fact that the vast majority of objects are safe to serialize and just a few of them aren't.

Marking an object as serializable (with an interface) doesn't magically make that object serializable, it was serializable all along, it's just that now you expressed something that the system could have found on his own, so I see no real good reason for serialization being the way it is now.

I think it was either a poor decision made by designers or serialization was an afterthought, or the platform was never ready to do serialization by default on all objects safely and consistently.

share edit
 
24 
You need to take special care when designing and implementing a class to make sure that instances will be serialised in a sensible way. The serializable interface actually mean: "I, as a programmer, has understood the consequences of serialization and permit the JVM to serialize this" –  Rolf Rander Jan 14 '09 at 12:11
 
@Rolf Rander: most of the time you need not take any care at all, just mark the class serializable. If serialization would have been ON by defaul on all objects the mindset of every developer would have been different too, it would have been something natural to do to make a class serializable... –  Pop Catalin Jan 14 '09 at 12:51
 
it would have added another concern to the list of good class design, like for example making sure you don't have memory leaks. Still, good class design more and more requires that your classes are serializable when they can be. –  Pop Catalin Jan 14 '09 at 14:52
 
@Rolf, or, it could mean "I don't care how X serializes it, but X needs it to be serializable so I will implement Serializable", where X can be some interoperable logical library (such as HttpSession, for instance, no one cares if a form object is serialized). –  MetroidFan2002 Jan 14 '09 at 17:27
3 
@StaxMan, because realizing later that a you need to serialize a class and you can't, can be very costly. It's one of those case where little extra effort pays. This is especially true if you're writing a library and someone else will consume it without the source code –  Pop Catalin Sep 1 '09 at 19:37

Not everything is genuinely serializable. Take a network socket connection, for example. You could serialize the data/state of your socket object, but the essence of an active connection would be lost.

share edit
 
 
This would be my problem and if I weren't smart enough to try to serialize socket, I would find my error during debugging. However, now I'm in a situation when I can't use Java serialization at all because of 3rd party class which doesn't implement Serializable for no good reason. –  Yoni Roit Jan 13 '09 at 23:05
4 
There are a few decent ways to handle this case, such as writing a Serializable wrapper class that knows how to read & write the key data of the 3rd party class; make the wrapped instance transient and override writeObject and readObject. –  Greg Case Jan 13 '09 at 23:56
 
Can you inherit from the required objects in your api and serialize those classes? –  Joel Coehoorn Jan 14 '09 at 0:31
 
@Joel: It's a good idea, but still a hack. I guess this whole thing is just another tradeoff went wrong. Thanks for your comments. –  Yoni Roit Jan 14 '09 at 10:35
 
This is one of those rare examples which illustrates that all we really need is implements NotSerializable :) –  Robert Grant Nov 27 '13 at 17:08

The main role of Serializable in Java is to actually make, by default, all other objects nonserializable. Serialization is a very dangerous mechanism, especially in its default implementation. Hence, like friendship in C++, it is off by default, even if it costs a little to make things serializable.

Serialization adds constraints and potential problems since structure compatibility is not insured. It is good that it is off by default.

I have to admit that I have seen very few nontrivial classes where standard serialization does what I want it to. Especially in the case of complex data structures. So the effort you'd spend making the class serializble properly dwarves the cost of adding the interface.

share edit
 

For some classes, especially those that represent something more physical like a File, a Socket, a Thread, or a DB connection, it makes absolutely no sense to serialize instances. For many others, Serialization may be problematic because it destroys uniqueness constraints or simply forces you to deal with instances of different versions of a class, which you may not want to.

Arguably, it might have been better to make everything Serializable by default and make classes non-serializable through a keyword or marker interface - but then, those who should use that option probably would not think about it. The way it is, if you need to implement Serializable, you'll be told so by an Exception.

share edit
 

I think the though was to make sure you, as the programmer, know that your object my be serialized.

share edit
 

Apparently everything was serializable in some preliminary designs, but because of security and correctness concerns the final design ended up as we all know.

Source: Why must classes implement Serializable in order to be written to an ObjectOutputStream?.

share edit
 

Having to state explicitely that instances of a certain class are Serializable the language forces you to think about if you you should allow that. For simple value objects serialization is trivial, but in more complex cases you need to really think things through.

By just relying on the standard serialization support of the JVM you expose yourself to all kinds of nasty versioning issues.

Uniqueness, references to 'real' resources, timers and lots of other types of artifacts are NOT candidates for serialization.

share edit
 

Read this to understand Serializable Interface and why we should make only few classes Serializable and also we shopuld take care where to use transient keyword in case we want to remove few fields from the storing procedure.

http://www.codingeek.com/java/io/object-streams-serialization-deserialization-java-example-serializable-interface/

share edit
 

Well, my answer is that this is for no good reason. And from your comments I can see that you've already learned that. Other languages happily try serializing everything that doesn't jump on a tree after you've counted to 10. An Object should default to be serializable.

So, what you basically need to do is read all the properties of your 3rd-party class yourself. Or, if that's an option for you: decompile, put the damn keyword there, and recompile.

share edit
 
2 
Serialization adds constraints and potential problems since structure compatibility is not insured. IMHO, It is good that it is off by default. –  Uri Jan 14 '09 at 0:09
 
I'm not certain what you mean by "structure compatibility". –  nes1983 Jan 14 '09 at 10:24

There are some things in Java that simply cannotbe serialized because they are runtime specific. Things like streams, threads, runtime,etc. and even some GUI classes (which are connected to the underlying OS) cannotbe serialized.

share edit
 

While I agree with the points made in other answers here, the real problem is with deserialisation: If the class definition changes then there's a real risk the deserialisation won't work. Never modifying existing fields is a pretty major commitment for the author of a library to make! Maintaining API compatibility is enough of a chore as it is.

share edit
 
 
This is not correct. You need to read the Versioning of Serializable Objects chapter of the Object Serialization Specification, which wouldn't exist if what you claim here was true. The class definition can change within rather wide limits before it becomes incompatible with prior serializations. And it certainly isn't the answer to the question. The real reason has to do with security concerns. –  EJP Oct 2 '13 at 5:38
 
@EJP, in the interest of truthiness I've edited my answer to reflect your points. The sentiment stands though, it is a big commitment that should definitely be opt-in rather than opt-out –  CurtainDog Oct 2 '13 at 22:28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值