You can use common methods
public <T> void insertData(Class<T> clazz, String fileName) { List<T> newList = new ArrayList<>(); }
but if you must use this insertData(String className, String fileName) contract insertData(String className, String fileName) , you cannot use generics, because the type of the list item cannot be resolved during Java compilation.
In this case, you may not use generics at all and use reflection to check the type before adding it to the list:
public void insertData(String className, String fileName) { List newList = new ArrayList(); Class clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e);
but without class information, you can only use Object , because you cannot drop your object in UnknownClass in your code.
source share