Pass the return type as a parameter in java?

Posted by jonderry on Stack Overflow See other posts from Stack Overflow or by jonderry
Published on 2011-03-12T00:04:32Z Indexed on 2011/03/12 0:10 UTC
Read the original article Hit count: 147

Filed under:

I have some files that contain logs of objects. Each file can store objects of a different type, but a single file is homogeneous -- it only stores objects of a single type.

I would like to write a method that returns an array of these objects, and have the array be of a specified type (the type of objects in a file is known and can be passed as a parameter).

Roughly, what I want is something like the following:

public static <T> T[] parseLog(File log, Class<T> cls) throws Exception {
    ArrayList<T> objList = new ArrayList<T>();
    FileInputStream fis = new FileInputStream(log);
    ObjectInputStream in = new ObjectInputStream(fis);
    try {
        Object obj;
        while (!((obj = in.readObject()) instanceof EOFObject)) {
            T tobj = (T) obj;
            objList.add(tobj);
        }
    } finally {
        in.close();
    }
    return objList.toArray(new T[0]);
}

The above code doesn't compile (there's an error on the return statement, and a warning on the cast), but it should give you the idea of what I'm trying to do. Any suggestions for the best way to do this?

© Stack Overflow or respective owner

Related posts about java