I have to read a binary file. I have to read two type of object “Company” and “Person”. Those object are represented by the two classes: Company and Person. Those classes are derived from “User” classes.
When I read this file I have two put the two object “Company” and “Person” into two different HashMap. My professor told me I have to use the keyword instanceof but I don’t understand how use it.
try
{
ObjectInputStream reader=new ObjectInputStream(new FileInputStream(fname));
while(reader.available()>0)
{
User obj=reader.readObject();
if(obj istanceOf Company)
...
else if(obj istanceOf Person)
}
}
catch(FileNotFoundException ffe)
{
System.err.println("Error: the file was not found!");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
is it right?
Try something like this:
In the above code,
objis the Object you read from the file, assuming that you don’t know its type. Also I’m assuming that you have aMapof companies calledcompaniesand aMapof persons calledpersons, and in either case you must have some sort of identifier (I’m calling itsomeId) to use as a key for storing the object in the corresponding map.