stackoverflow(翻译Serializable)

来源:互联网 发布:海关数据开发客户 编辑:程序博客网 时间:2024/06/12 22:04

Why Java needs Serializable interface?

up vote69 down vote favorite
27

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 addimplements Serializable - why didn't they make everything serializable and that's it?

What am I missing?

shareedit
 
 
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

activeoldest votes
up vote79 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 thepersisted 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.

shareedit
 
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. – gbtimmonJul 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 ? – GeekAug 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. – McDowellAug 22 '12 at 8:05
 
@McDowell Why does the order matter ? – GeekAug 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 RoitMar 6 '13 at 19:55
up vote28 down vote

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.

shareedit
 
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 RanderJan 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 CatalinJan 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 CatalinJan 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). – MetroidFan2002Jan 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 CatalinSep 1 '09 at 19:37
up vote16 down vote

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.

shareedit
 
 
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 RoitJan 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 CaseJan 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 isimplements NotSerializable :) – Robert GrantNov 27 '13 at 17:08
up vote11 down vote

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.

shareedit
 
up vote8 down vote

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.

shareedit
 
up vote4 down vote

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

shareedit
 
up vote1 down vote

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?.

shareedit
 
up vote1 down vote

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.

shareedit
 
up vote1 down vote

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/

shareedit
 
up vote0 down vote

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.

shareedit
 
2 
Serialization adds constraints and potential problems since structure compatibility is not insured. IMHO, It is good that it is off by default. – UriJan 14 '09 at 0:09
 
I'm not certain what you mean by "structure compatibility". – nes1983Jan 14 '09 at 10:24
up vote0 down vote

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.

shareedit
 
up vote-1 down vote

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.

shareedit
 
 
This is not correct. You need to read theVersioning 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. – EJPOct 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 – CurtainDogOct 2 '13 at 22:28
0 0
原创粉丝点击