I need to write a java method which takes a class (not an object) and then creates an ArrayList with that class as the element of each member in the array. Pseudo-code exam
You can use Generic methods
public void insertData(Class clazz, String fileName) {
List 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.