'How to initialize a list of a class type received as a parameter?

I am a beginner in Java.

How do I initialize a list of a class type received as a parameter? I have a method that takes in a Class<?> argument as a parameter, and I want to create a list of this class type.

public List<?> returnList(Class<?> listItemType) {
    //create a list of type "listItemType"
    //populate the list
    //return the list
}

I have tried doing

List<listItemType> list = new ArrayList<listItemType>()

but VSCode shows listItemType cannot be resolved to a type.

I have also tried <? extends listItemType>, <listItemType.getName()> and the below code, but they don't seem to work either.

Object obj = listItemType.getDeclaredConstructor().newInstance();
List<obj.getClass()> = new ArrayList<obj.getClass()>();


Solution 1:[1]

What you need is a generic method.

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type.

This is a full example:

public class NewMain {

    private static class Foo {

        public Foo() {
        }
    }
    
    public static void main(String[] args) {
        // TODO code application logic here
        List<Foo> foos = returnList(Foo.class);
        System.out.println(foos.get(0));
    }
    
    public static <T> List<T> returnList(Class<T> listItemType) {
        List<T> list = new ArrayList<>();
        try {
            T obj = listItemType.getConstructor().newInstance();
            list.add(obj);
        } catch (Exception ex) {
            Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
        }
        return list;
    }
    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1