Using generics in Android Java code

I am new to Java, so I'm not sure if this is possible. Basically I need to de-serialize the file into an object of a certain 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, so I can tell what type I want in.readObject() to print its output and return it.

Hope this makes sense ... again, I probably did not understand the generics properly, and this is actually impossible or appropriate.

Thanks D.

+4
source share
2 answers

I'm not sure about Android (or any restrictions that may 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 name it like

 MyClass myObj = getObject("in.txt"); 

This will give you a warning without warning, though, since the compiler cannot be sure that you can apply the resulting object to the provided type, so it won’t exactly type safe. You must be sure that what you get from the input stream can indeed be passed to this class, otherwise you will get a ClassCastException. You can suppress the warning by annotating the method with @SuppressWarnings("unchecked")

+7
source

Just looking at it. How do I make a method a return type? 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); } 
+1
source

All Articles