Using generics in Android Java code
Solution 1
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")
Solution 2
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);
}
Edvin Keskin
Updated on June 05, 2022Comments
-
Edvin Keskin almost 2 years
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.
-
Edvin Keskin over 13 yearsFantastic! That's even tidier, and it worked! :o) Thanks very much!
-
Nathan Schwermann over 13 yearsAwesome, what interfaces or constructor would MyClass need for this to work
-
Andrei Fierbinteanu over 13 yearsWell, it's basically just a cast. So whatever was needed by the input stream, using Object instead of T, is still needed. But no new requirements for interfaces or constructors are added.
-
pAkY88 over 13 yearsThe (T) cast is unsafe and generates a warning for good reason. Using this method can cause type polution if the type you are reading is itself a generic type. For example
List<String> foo = getObject('file')
will put any list it happens to read intofoo
, even if it contains something else than Strings. This mistake would only be noticed later when you start using he list.