2

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?

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

The warning about unchecked type is because MyList is using generics, MyList<?> would not cause a warning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.