Here is an example program. Right by the comment will fail, I want to know if I can create a method that achieves this functionality of creating a list at runtime.
import java.util.ArrayList;
import java.util.List;
public class ListMaker
{
public static List<?> makeList(Class clazz)
{
// I want to do something like this
return new ArrayList<clazz>();
}
public static void main(String[] args)
{
Vo object = new Vo(100);
ArrayList<Vo> list = makeList(Vo.class);
list.add(object);
}
}
class Vo
{
int i;
public Vo(int i){this.i = i;}
}
This is not how you use generics and you can't actually do in Java what you are trying to do (creating a makeList method that returns a specific ArrayList using a class parameter that should be then used as T).
Remember that generics are just a compiler feature and that for the effect of type erasure those ArrayList<T> will become simple ArrayList when compiled to bytecode (you'll be only able to retrieve details about the original type parameter using the reflection classes that extract that information from the stringified method signature at runtime).
The T in ArrayList<T> it's not a variable, and you can't create a parametrized type at runtime, like you are trying to do. You could use a plain old ArrayList that contains every kind of Object without type checking.
In your main method, the type of the List is known (it's a List<Vo>). In this situation you don't need to pass a Class object as a generic method will do:
public static <T> List<T> makeList()
{
return new ArrayList<T>();
}
This can be called by writing List<Vo> list = makeList();
However I don't see why you need a method for this (what's wrong with List<Vo> list = new ArrayList<Vo>();?
If the type T is not known and all you have is a Class or a Class<?> object, what you are trying to do doesn't make sense in Java. At runtime, there is no such thing as a List<String> or a List<Vo> as all type information is erased. There are only raw Lists at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With