Question

I can write a list to a file with this code:

MyList<Integer> l = new MyList<Integer>();
//...

FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream writer = new ObjectOutputStream(fos);

writer.writeObject(l);
writer.close();

Now I want to read the list from the file and I tried with this code:

MyList<Integer> list = new MyList<Integer>();
//...

FileInputStream fis = new FileInputStream(filename);
ObjectInputStream reader = new ObjectInputStream(fis);

list = (MyList<Integer>) reader.readObject();   
reader.close();

But now I get a SuppressWarnings unchecked from Eclipse and I have to check for a ClassNotFoundException. Why is that and how can I prevent this?

Was it helpful?

Solution

Serialization can be used to transfer objects to other applications. It's possible that the serialized class is not present in the application that reads the object. Since the ObjectOutputStream only stores the contents of the fields and not the code, the reading applications needs to have the actual code for the written classes. If it is not present, a ClassNotFoundException is thrown.

As for the unchecked type: Try reading it into an Object instance first and then use the "instanceof" operator to check if it is actually of type MyList. See also here for the generic part: How to avoid unchecked cast warnings with Java Generics

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top