Reputation: 13
Below is a piece of code for serializing objects , but using generics. There was no .ser file created when i executed this method. I am sure I mite be missing on some important concept of generics here. Please help me out !
public <T> void saveToDisk(List<T> objectlist) {
// TODO Auto-generated method stub
System.out.println(path);
if ("domain_pojo.Customer".equals(objectlist.getClass().getName()))
file = "/customer.ser";
else if ("domain_pojo.Employees"
.equals(objectlist.getClass().getName()))
file = "/employee.ser";
else if ("domain_pojo.Orders".equals(objectlist.getClass().getName()))
file = "/order.ser";
try {
FileOutputStream fos = new FileOutputStream(path + file);
// Create ObjectOutputStream to write object
ObjectOutputStream objOutputStream = new ObjectOutputStream(fos);
// Write object to file
System.out.println("Size of objectlist is :" + objectlist.size());
// objectlist.add(null);
for (T obj : objectlist) {
objOutputStream.writeObject(obj);
objOutputStream.reset();
}
objOutputStream.close();
} catch (IOException e) {
new FileParsingException(e, e.getMessage());
}
}
Upvotes: 1
Views: 54
Reputation: 24134
if ("domain_pojo.Customer".equals(objectlist.getClass().getName()))
This line is always false (and the case is same with other else IF blocks as well) as the value of objectlist.getClass()
will always be java.util.List.
You should instead pass Class<T> clazz
and use that in the comparison.
On a related note, it would be better to have the class implement some interface method that returns the file name, instead of hard-coding like this.
Upvotes: 2