Showing posts with label Serialization. Show all posts
Showing posts with label Serialization. Show all posts

Sunday, 14 May 2017

InvalidClassException Exception in Java


java.lang.Object
            java.lang.Throwable
                        java.lang.Exception
                                    java.io.IOException
                                                java.io.ObjectStreamException
                                                            java.io.InvalidClassException


public class InvalidClassException extends ObjectStreamException

Throws when the Serialization runtime detects a problem with a Class:
1) The serial version of the class does not match that of the class descriptor read from the stream.
2) The class contains unknown datatypes.
3) The class does not have an accessible no-arg constructor.
4) The class is not public.
5) The class implements only one of writeObject or readObject methods.



Thursday, 13 April 2017

Java Serialization with Aggregation (HAS-A Relationship)

If a class has a reference to another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.

Address.java
class Address { 
     String hNo,city,state; 
     public Address(String hNo, String city) { 
           this.hNo=hNo; 
           this.city=city; 
     } 
}

Employee.java
import java.io.Serializable; 
public class Employee implements Serializable { 
     int id
     String name
     Address address;//HAS-A 
     public Student(int id, String name) { 
           this.id = id
           this.name = name
     } 

Since Address is not Serializable, we are getting NotSerializableException while serializing the instance of Employee class.

How to fix the Serialization in the case of Association?
Using the transient keyword:
In case the class refers to non-serializable objects and these objects should not be serialized, then, you can declare these objects as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.

Using the static keyword:
In serialization, static variables are not serialized, so during deserialization, static variable value will load the class.

Make it a Serializable object:
All the objects within an object must be Serializable.

Sunday, 13 December 2015

Generate serialVersionUID using Java Program

serialVersionUID can be generated by using getSerialVersionUID() method of the ObjectStreamClass class.

SerialiazedClass.java
package com.serial;
importjava.io.Serializable;

class SerialiazedClass implements Serializable {
     String name;
     public voidsetName(String name) {
           this.name = name;
     }
}

GenerateSerialVerUID.java

import java.io.ObjectStreamClass;
public class GenerateSerialVerUID {
    
     public static void main(String[] args) {
          
           Class hashClass = SerialiazedClass.class;
          
           ObjectStreamClass osc = ObjectStreamClass.lookup(hashClass);
           long serialID = osc.getSerialVersionUID();

           System.out.println(serialID);
     }
}
Output:
1623809446810541828

Saturday, 12 December 2015

How to generate serialVersionUID in Java?

Generate serialVersionUID of Employee class

import java.io.Serializable;
public class Employee implements Serializable {
     private String name;
     publicEmployee(String name) {
           this.name = name;
     }
     public String getName() {
           return name;
     }
}

1. serialver command
JDK has a build in command called “serialver” to generate the serialVersionUID automatically.


C:\Users\awadh\Desktop>javac Employee.java
C:\Users\awadh\Desktop>serialver Employee
Employee:  private static final long serialVersionUID = -6607742892470200720L;




2. serialver tool


Run command: serialver –show
C:\Users\awadh\Desktop>serialver -show
Put the class description in the tool and click on the show button.
private static final long serialVersionUID = -6607742892470200720L;



3. Using Eclipse IDE

Friday, 11 December 2015

Why SerialVersionUID is static?


The serialization runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that is compatible with respect to serialization.

If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.

The serialVersionUID determines compatibility between different versions of a class. Since the property is bound to the class, it has to be made static.


static variables are not serialized with the object.

However, serialVersionUID is a must in serialization process.


When an object is serialized, the serialVersionUID is serialized along with the other contents. This is one exception to the general serialization rule that, “static fields are not serialized”.

References:
http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html#4100

Need externalizable when we already have serializable

When you serialize any object using serializable, apart from fields, all objects that belong to object map and that can be reached using instance variable will also be serialized.

For example:
  • If you have Employee class and its superclass is the person then it will serialize all superclass objects (such as the person) until it reaches "Object" class.
  • Similarly, if Employee has an instance variable of address class then it will serialize whole object map of address also.

Do you really want this much overhead when all you want to serialize is empId and empName.


JVM uses reflection when you use serializable which is quite slow.

While serializing, information about class description which includes the description of its superclass and instance variable associated with that class also get stored in the stream. Again this is also a performance issue.

Monday, 26 October 2015

What are disadvantages of deep cloning using Serialization?

Disadvantages of using Serialization to achieve deep cloning

1. Serialization is more expensive than using object.clone().

2. Not all objects are serializable.

3. Serialization is not simple to implement for deep cloned object.

Friday, 9 October 2015

java.io.NotSerializableException

java.io.NotSerializableException is thrown when the object is not eligible for the serialization. We must implement the Serializable interface to make the class eligible for the serialization. This is a marker interface which tells the JVM that the class can be serialized.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

class Student {
      private String id;

      public String getId() {
            return id;
      }

      public void setId(String id) {
            this.id = id;
      }
}

public class NotSerializableExceptionTest {
      public static void main(String[] args) throws IOException{
            //Create FileOutputStream to create file
            FileOutputStream out = new FileOutputStream("student.dat");

            //Create ObjectOutputStream
            ObjectOutputStream outputStream = new ObjectOutputStream(out);

            //Create objects
            Student obj = new Student();
            obj.setId("001");

            //Write objects to stream
            outputStream.writeObject(obj);

            //Always close the stream
            outputStream.close();
      }
}

Output:
      Exception in thread "main"java.io.NotSerializableException: Student
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at NotSerializableExceptionTest.main(NotSerializableExceptionTest.java:30)

How to fix java.io.NotSerializableException?

Student class must implement the serializable interface.

Serialization of Enum Constants

Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form.

To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method.

To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing the constant's enum type along with the received constant name as arguments.

Important points:


enum constants are serialization cannot be customized with writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods, enum types are ignored during serialization and deserialization by these methods.

All enum types have a fixed serialVersionUID of 0L.


Related Posts Plugin for WordPress, Blogger...