简体   繁体   中英

Pass the return type as a parameter in java?

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?

You can't have generic arrays, so just return the ArrayList from your method:

    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;
    }

Then, when you know the actual type, do the cast then. So assuming you know that T is actually an Integer at some point, do this:

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

I can't see how this would be a good programming practice. Essentially you're trying to say "I want to arbitrarily determine the return type without sacrificing type-safety." which is a bit awkward.

I would say your 'best' option would be to just return ArrayList<T> instead of going for an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM