See the below program,
package test;
import java.io.*;
import java.util.Date;
public class HeadQuarterEmpProcessor {
private void serialize(){
CompanyEmployee emp = new CompanyEmployee();
emp.lName = "John";
emp.fName = "Smith";
emp.salary = 50000;
emp.address = "12 main street";
emp.hireDate = new Date();
FileOutputStream fOut=null;
ObjectOutputStream oOut=null;
try{
fOut= new FileOutputStream("c:\\NewE
mployee.se
r");
oOut = new ObjectOutputStream(fOut);
oOut.writeObject(emp); //serializing employee
System.out.println(
"An employee is serialized into c:\\NewEmployee.ser");
}catch(IOException e){
e.printStackTrace();
}finally{
try {
oOut.flush();
oOut.close();
fOut.close();
emp.fName = "Smith - After Serialization";
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private void deserialize(){
FileInputStream fIn=null;
ObjectInputStream oIn=null;
try{
fIn= new FileInputStream("c:\\NewEm
ployee.ser
");
oIn = new ObjectInputStream(fIn);
//de-serializing employee
CompanyEmployee emp = ( CompanyEmployee ) oIn.readObject();
System.out.println( "Deserialized " + emp );
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundExcept
ion e){
e.printStackTrace();
}finally{
try {
oIn.close();
fIn.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
HeadQuarterEmpProcessor processor = new HeadQuarterEmpProcessor() ;
processor.serialize() ;
processor.deserialize() ;
}
}
class Employee{
String lName;
static String fName;
transient double salary;
java.util.Date hireDate;
String address;
Employee( String name ){
lName = name ;
}
}
class CompanyEmployee extends Employee implements java.io.Serializable {
final int constant ;
CompanyEmployee(){
super( "sd" ) ;
constant = 1000 ;
}
public String toString(){
StringBuffer buf = new StringBuffer() ;
buf.append( "Last Name: " + lName ) ;
buf.append( "\nFirst Name: " + fName ) ;
buf.append( "\nsalary: " + salary ) ;
buf.append( "\nconstant: " + constant ) ;
return buf.toString() ;
}
}
I understand there is a error in the program that the Employee class doesn't have default constructor... but the exception stack points a different line or method call for the exception,
java.io.InvalidClassExcept
ion: test.CompanyEmployee; no valid constructor
at java.io.ObjectStreamClass.
<init>(Obj
ectStreamC
lass.java:
455)
at java.io.ObjectStreamClass.
lookup(Obj
ectStreamC
lass.java:
297)
at java.io.ObjectOutputStream
.writeObje
ct0(Object
OutputStre
am.java:10
35)
at java.io.ObjectOutputStream
.writeObje
ct(ObjectO
utputStrea
m.java:302
)
at test.HeadQuarterEmpProcess
or.seriali
ze(HeadQua
rterEmpPro
cessor.jav
a:22)
at test.HeadQuarterEmpProcess
or.main(He
adQuarterE
mpProcesso
r.java:67)
See the exception is reported in the serialize method than the deserialize method, why?
Start Free Trial