I want to create a list from a Class
variable.
...
Class clazz = someObject.getClass();
List<clazz> myList = new ArrayList<clazz>(); // this line is a compilation error
...
How I can do it?
EDIT: I think you are getting it wrong. For example, if someObject
is a Car
, then myList
type should be List<Car>
. I want to treat my clazz variable as a type, in some way.
EDIT:
As Boris the Spider pointed out in the comments it actually is possible by using a generic method, but with a slight modification:
Instead of using the normal Class
object, use the generic version Class<? extends [Type of someObject]>
.
Example:
public static void main(String[] args){
Test t = new Test();
Class<? extends Test> testClass = t.getClass();
List<? extends Test> list = createListOfType(testClass);
}
private static <T> List<T> createListOfType(Class<T> type){
return new ArrayList<T>();
}
Of course you can also just go with
public static void main(String[] args){
Test t = new Test();
List<? extends Test> list = createListOfType(t);
}
private static <T> List<T> createListOfType(T element){
return new ArrayList<T>();
}
OLD POST:
You can't.
You can't, because Java needs to know the generic type you want to use for the ArrayList
at compile time. It's possible to use Object
as type though.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments