You can use Generic methods
public <T> void insertData(Class<T> clazz, String fileName) {
List<T> newList = new ArrayList<>();
}
but if you should use this contract insertData(String className, String fileName), you cannot use generics because type of list item cannot be resolved in compile-time by Java.
In this case you can don't use generics at all and use reflection to check type before you put it into 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); // provide proper handling of ClassNotFoundException
}
Object a1 = getSomeObjectFromSomewhere();
if (clazz.isInstance(a1)) {
newList.add(a1);
}
// some additional code
}
but without information of class you're able use just Object because you cannot cast your object to UnknownClass in your code.
String className? It'd be easier if you could pass the actualClassobject in, likeinsertData(ExampleClass.class, fileName).