Pass return type as parameter in java?

I have files containing object logs. Each file can store objects of a different type, but one file is homogeneous - it stores only objects of one type.

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

Roughly speaking, I want 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 does not compile (there is an error in the return statement and a warning when creating), but it should give you an idea of ​​what I'm trying to do. Any suggestions on the best way to do this?

+3
source share
2 answers

, ArrayList :

    public static <T> ArrayList<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;
    }

, , . , , T , :

Integer[] array = ((ArrayList<Integer>) myList).toArray(new Integer[myList.size()]);
+4

, . , : " , ". .

, "" , ArrayList<T> .

+1

All Articles