• Post Reply Bookmark Topic Watch Topic
  • New Topic

Check out this Serialization Stuff !  RSS feed

 
Jose Campana
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I'm back and posting once more, I'm sorry to bother you guys, but I just had to do this. I need to have this one cleared up and understood ASAP.
Here it goes, check the following code:



The preceding code throws an Exception at Runtime of course, because it HAS an instance of a Non-Serializable class (NonSerial).

However, If I don't assign an Object to that particular reference variable, like this:



The result is that the Object gets Serialized with no problems. Why is that?

Why does it Only Matter when the reference variable from a Non-serializable class has an Object assigned to it?

Hope you guys can Help Me,
Thankful as always,
Jose
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's the object itself that gets serialized, not the reference.

In this case, it's not serializing anything, because the variable is not pointing to any object but is null instead. Therefore it will not throw an error.

In the first case, the reference does point to an object, and because the reference is not transient, the JVM tries to serialize it. It cannot be serialized however, and therefore will throw the error.
 
Jose Campana
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob, for the intensive personalized care you have taken to answer my questions today.
I understand the concept of Serialization better now, after reading your response, But I have one remaining doubt about it...
What's the logic the compiler follows when allowing an instance variable that belongs to a non-Serializable class to be inside a Serializable Class?

Why does it allow such thing? Isn't it risky to have an instance variable like that, even when no Object has yet been assigned?

Take care,
Jose
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it is risky, but if you never serialize the object then it's no problem whatsoever.

Also, if you assign an object of a subclass (or implementing class in the case of interfaces) that IS serializable, then it will also work perfectly. I guess Sun just think the programmer is responsible for making his class fully serializable.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look into the transient keyword. Do you think that might have been a good idea for this variable?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!