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.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;



public class Test
{
  public static class Toto 
  {
    public String me;    
  }
  
  public static class Toto2 extends Toto implements Serializable
  {
    public String you;
    public String toString()
    {
      return me+" "+you;
    }
  }
  
  public static void main(String[] argsthrows Exception
  {
    Toto2 t = new Toto2();
    t.me = "it's me";
    t.you = "it's you";
    System.out.println("t="+t);
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(b);
    oos.writeObject(t);
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(b.toByteArray()));
    System.out.println("u="+ois.readObject());
  }
}

will output:
t=it's me it's you
u=null it's you

using System;
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.

Comments

comments powered by Disqus