Here’s my code:
class Collar {
int size;
}
class Dog implements Serializable {
int weight;
transient Collar c;
public Dog(int weight, int size) {
this.weight = weight;
c = new Collar();
c.size = size;
}
public void writeObject(ObjectOutputStream os) throws Exception {
os.defaultWriteObject();
os.writeInt(c.size);
}
public void readObject(ObjectInputStream is) throws Exception {
is.defaultReadObject();
c = new Collar();
c.size = is.readInt();
}
}
public class test {
public static final String FILE_REVISION = "$Revision$";
public static void main(String ar[]) throws Exception {
Dog dOut = new Dog(20, 2);
System.out.println("DOut Weight: " + dOut.weight + " Size: " + dOut.c.size);
FileOutputStream fo = new FileOutputStream("Dog.ser");
ObjectOutputStream os = new ObjectOutputStream(fo);
os.writeObject(dOut);
FileInputStream fi = new FileInputStream("Dog.ser");
ObjectInputStream is = new ObjectInputStream(fi);
Dog dIn = (Dog) is.readObject();
System.out.println("DIn Weight: " + dIn.weight + " Size: " + dIn.c.size);
}
}
and here’s the output:
DOut Weight: 20 Size: 2
Exception in thread "main" java.lang.NullPointerException
at test.main(test.java:55)
Line 55 is the last line of code that has System.out.println()
The program is able to get back the serializable object, which is Dog here. However, its not able to create a new ‘containment’ object, Collar, when I’m reading back using custom readObject method. Where am I going wrong?
As you can see the output is NullPointerException in ‘dIn.c.size’ statement. Even though I’m setting up c as a new object in custom readObject method, it’s not working really.
Because
Collar cistransientinsidereadObjectyou need to initializecFirstHere you need to initialize
Cfirst.Both method signatures are wrong they should be like below:
You can read more details about Serialization here