Tuesday, December 22, 2009

ObjectStreamClass

ObjectStreamClass



java.io.ObjectStreamClass class implements Serializable interface and it describes the details of JAVA classes. ObjectStreamClass plays major role in serialization, it offers us to know about

  • getName() - Class Name
  • getSerialVersionUID() - serialVersionUID
  • getFields()- fields and its type
  • forClass() - returns class in local JVM
  • lookup(Class<?> cl)/lookupAny(Class<?> cl) - used to get Classdescribtor object for particular class



Since this class offers to know about data phase of class, it will be useful in various place. Up to JDK 5.0, this class used to create class describtor only for the java.io.Serializable or java.io.Externalizable using lookup() API. In JDK 6.0, this class usage extended to offer for non-serializable classes using lookupAny(Class<?> cl)




import java.io.ObjectStreamClass;
import java.io.Serializable;

public class ObjectStreamClassTest {

public static class EmployeeBean implements Serializable {
String name;
String designation;
}

/**
* @param args
*/
public static void main(String[] args) throws Exception {
Class<EmployeeBean> employeeBean = (Class<EmployeeBean>) Class
.forName("ObjectStreamClassTest$EmployeeBean");

ObjectStreamClass oscT = ObjectStreamClass.lookup(employeeBean);
System.out.println("Old look up not gets for ObjectStreamClass: "
+ oscT);

oscT = ObjectStreamClass.lookupAny(employeeBean);
System.out.println("lookupAny gets for ObjectStreamClass: "
+ oscT.getSerialVersionUID());
System.out.println(oscT.getField("name"));

EmployeeBean emp = (EmployeeBean)oscT.forClass().newInstance();
System.out.println("Name :"+ emp.name + " Desig: " + emp.designation);

}
}


Output could like below:
Old look up not gets for ObjectStreamClass: ObjectStreamClassTest$EmployeeBean: static final long serialVersionUID = 7687813253144298513L;
lookupAny gets for ObjectStreamClass: 7687813253144298513
Ljava/lang/String; name
Name :null Desig: null



Remove implementing Serializable in EmployeeBean and run this program. We will see the inconsistent in serialVersionUID, fields. However, we could able to create instance of JAVA object using ObjectStreamClass class.



Note:
Compile and run the above code using the compiler source and target in JDK 6.0 version.

No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com