views:

115

answers:

2

Hi folks,

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.

+1  A: 

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")

Andrei Fierbinteanu
Fantastic! That's even tidier, and it worked! :o) Thanks very much!
DanyW
Awesome, what interfaces or constructor would MyClass need for this to work
schwiz
Well, 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.
Andrei Fierbinteanu
The (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 into `foo`, even if it contains something else than Strings. This mistake would only be noticed later when you start using he list.
Wouter Coekaerts
A: 

Having just seen this http://stackoverflow.com/questions/450807/java-generics-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);
    }
DanyW