I am new to the world of Generics and am trying to write a utility class that will take a list of Objects and persist it to the store and then retrieve it back.
This is what I wrote to save the list:
public static void saveListToStore(Context ctx, String fileName, list<Object> listToStore) throws IOException
{
String elemValue = "";
Gson gson = new Gson();
try {
FileOutputStream fileOutputStream = ctx.openFileOutput(fileName, ctx.MODE_PRIVATE);
elemValue= gson.toJson(listToStore);
fileOutputStream.write(elemValue.getBytes());
objectOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
However when I try to retrieve, I will not be aware of the type of object that was there in the list and cannot rebuild it back. I do not want to put type comparisons as I would like to save any type of custom class and the list can be huge.
I want to deduce the type from the content itself. I was thinking of saving the type as the first line and then the data. So on retrieve I can get the type first and then typecast the objects. However is there any other cleaner way of achieving this ?