I am trying to read two different lists from a binary file. One list is of type Flight and the other is of type Customer. I tried to use instanceof operator but the compiler shows error as
Cannot perform instanceof check against parameterized type List. Use the form List instead since further generic type information will be erased at runtime.
As the items have to be read using a loop until all the lists are read, I’m not sure how to implement this logic.
My code is as follows:
public static void readFromFile() throws Exception {
List<Flight> flightList;
List<Customer> customerList;
//Create new input stream object
objInStream = new ObjectInputStream(new FileInputStream(fileLocation));
//Check if file exists
if(!fileLocation.exists()) {
//create new file
fileLocation.createNewFile();
}
Object o;
while((o = objInStream.readObject()) != null) {
//Compiler shows error
if(o instanceof List<Flight>)
flightList = (List<Flight>) o;
else if(o instanceof List<Customer>)
customerList = o;
}
}
You cannot check if
ois a “list of ____.” You can check if the elements ofoare __, though. Or you could just mark it explicitly.But this is a normal consequence of type erasure. Generics are only a compile-time annotation. Your program will not keep the generics at runtime!