Reputation: 47
I am loading an object from serialized form:
private void loadSerialisedIntersection() throws IOException{
try{
FileInputStream f_in = new FileInputStream(getPath());
obj_in = new ObjectInputStream (f_in);
obj = obj_in.readObject();
if(!(obj instanceof Intersection)) {
throw new IOException("Wrong class");
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I was wondering if it is a good idea to cast to the type of object I am expecting? I have seen this recommended but I can only imagine it would cause issues. If this is the right thing to do could you please explain why?
Thanks
Upvotes: 0
Views: 72
Reputation: 880
You should cast it to the expected type because that is the point of typed languages. You are already checking if that object is a correct instance type. When you finish with ObjectInputStream close it and make obj_in and obj a scope variable not a field (I'm assuming this).
Upvotes: 2