I'm a newbie in Java so I'm not sure if this is possible. Basically I need to de-serialise a file into an object of a given type. Basically the method will do this:
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
MyClass newObject = (MyClass)in.readObject();
in.close();
return newObject;
I would like this method to be generic, therefore I can tell it what type I want to in.readObject()
to cast its output into, and return it.
Hope this makes sense...then again, I probably didn't understand generics properly and this is not actually possible, or advisable.
Thanks, D.
I'm not sure about Android (or any limitations it might have), but in Java you can do something like this:
public static <T> T getObject(String filename) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
T newObject = (T) in.readObject();
in.close();
return newObject;
}
and then call it like
MyClass myObj = getObject("in.txt");
This will give you an unchecked cast warning though, since the compiler can't be sure you can cast the object received to the type provided, so it's not exactly type safe. You need to be sure that what you're getting from the input stream actually can be cast to that class, otherwise you will get a ClassCastException. You can suppress the warning by annotating the method with @SuppressWarnings("unchecked")
Having just seen this How do I make the method return type generic? I am going to try the following:
public <T> T deserialiseObject(String filename, Class<T> type)
throws StreamCorruptedException, IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
Object newObject = in.readObject();
in.close();
return type.cast(newObject);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With