简体   繁体   中英

Get Object type of class for ArrayList

So, I've tried to get object type of a given class to parse into ArrayList Example:

public class Util{
    public static void makeArray(String tag, Class<?> forClass) {
        ArrayList<?> list = new ArrayList();
    }
}

How can I replace <?> with forClass object type? So back in main method when I call

Util.makeArray("names", String.class);

It would create ArrayList<String> and if I say

Util.makeArray("ages", int.class);

It would resolve it to ArrayList<Integer>

And if it is not even done this way, show how.

You would use a method type parameter.

public static <T> void makeArray(String tag, Class<T> forClass) {
    ArrayList<T> list = new ArrayList<>();
}

This can be called using Util.<String>makeArray("names", String.class) or you can let the compiler infer T by omitting the <String> .

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