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 example:
public void insertData(String className, String fileName) {
ArrayList<className> newList = new ArrayList<className>();
}
How can I accomplish this in Java?
You can use Generic methods
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:
but without information of class you're able use just
Object
because you cannot cast your object to UnknownClass in your code.Vlad Bochenin gives a good way but it makes no sense to provide a T generic that derives from nothing in your method.
It puts zero constraints in the code of
insertData()
that manipulates the list.You will be forced to do cast in the code and it defeats the purpose of Generics.
I suppose you want manipulate some instances of known classes in
insertData()
.And if you use generic in your case, it would have more meaningful if you have subtypes of classes to manipulate.
In this way, you could have a method that accepts a base type and its subclases.
My guess is that what you really want to do is to return the generated
List
. This is what that might look like:This is how it could be used: