How to have Java method return generic list of any type?

user1768830 picture user1768830 · Jul 24, 2013 · Viewed 172.5k times · Source

I would like to write a method that would return a java.util.List of any type without the need to typecast anything:

List<User> users = magicalListGetter(User.class);

List<Vehicle> vehicles = magicalListGetter(Vehicle.class);

List<String> strings = magicalListGetter(String.class);

What would the method signature look like? Something like this, perhaps(?):

public List<<?> ?> magicalListGetter(Class<?> clazz) {
    List<?> list = doMagicalVooDooHere();

    return list;
}

Answer

Joop Eggen picture Joop Eggen · Jul 24, 2013
private Object actuallyT;

public <T> List<T> magicalListGetter(Class<T> klazz) {
    List<T> list = new ArrayList<>();
    list.add(klazz.cast(actuallyT));
    try {
        list.add(klazz.getConstructor().newInstance()); // If default constructor
    } ...
    return list;
}

One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()).