The readObject() method of the ObjectInputStream returns Object and that needs to be casted to appropriate type. what if I serialize an array of String, do I get array of Objects or Array of Strings. I tried this below. String[] arr = (String[]) objArr; fail in general case.
but after Serialization, when I cast the Object returned from readObject() to String[], I do not get any Exception. so what is that returning?
the method signature of readObject() is
public final Object readObject() throws IOException, ClassNotFoundException which indicates it returns the Object.
why casting it to String[] works here, but in a more general case (as shown below) it fails.
public class UpcastDownCast {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//the below three lines give runtime Exception
Object[] objArr = {new String("hello"), new String("world")};
String[] arr = (String[]) objArr;
System.out.println(Arrays.toString(arr));
String[] arrV={new String("Car"), new String("Bike")};
FileOutputStream of= new FileOutputStream("file.ser");
ObjectOutputStream oos=new ObjectOutputStream(of);
oos.writeObject(arrV);
FileInputStream fi = new FileInputStream("file.ser");
ObjectInputStream ois= new ObjectInputStream(fi);
String[] t2= (String[]) ois.readObject();
System.out.println("after "+ Arrays.toString(t2));
}
}