Java Serialization vs .NET Serialization - Java Perverse?
Did you know what happens in Java when you serialize a subclass of a non serializable class? I was surprised by the answer: it works!Unfortunately it is not a good thing, because it will serialize fields from your subclass and no fields from the parent class. So you'll end up with a half serialized instance.
In .NET, it breaks at runtime, throwing an exception, which is I think, much more logical, because then you don't end up with half data somewhere.
- Java Code:
import java.io.ByteArrayInputStream; |
will output:
t=it's me it's you
u=null it's you
- .NET Code:
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication
{
public class Toto
{
public string me;
public override string ToString()
{
return me;
}
}
[Serializable]
public class Toto2 : Toto
{
public string you;
public override string ToString()
{
return you + " " + me;
}
}
class Program
{
static void Main(string[] args)
{
Toto2 t = new Toto2();
t.me = "it's me";
t.you = "it's you";
using (FileStream fs = File.Create(@"c:\test.bin"))
{
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(fs, t);
}
Console.WriteLine("t=" + t.ToString());
Toto2u = null;
using (FileStream fs = File.Open(@"c:\test.bin", FileMode.Open))
{
BinaryFormatter bFormatter = new BinaryFormatter();
u = (Toto2)bFormatter.Deserialize(fs);
}
Console.WriteLine("u="+u.ToString());
Console.ReadKey();
}
}
}
will throw an exception.