Pass the return type as a parameter in java?
<p>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.</p>

<p>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).</p>

<p>Roughly, what I want is something like the following:</p>

<pre><code>public static &lt;T&gt; T[] parseLog(File log, Class&lt;T&gt; cls) throws Exception {
    ArrayList&lt;T&gt; objList = new ArrayList&lt;T&gt;();
    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]);
}
</code></pre>

<p>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?</p>
