Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generics in Android Java code

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.

like image 326
codedog Avatar asked Feb 26 '23 04:02

codedog


2 Answers

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

like image 180
Andrei Fierbinteanu Avatar answered Mar 07 '23 04:03

Andrei Fierbinteanu


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);
    }
like image 41
codedog Avatar answered Mar 07 '23 05:03

codedog