tehAnswer
tehAnswer

Reputation: 1018

Create a parametrized List from a Class variable

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.

Upvotes: 3

Views: 3028

Answers (3)

fachammer
fachammer

Reputation: 181

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.

Upvotes: 4

Suresh Atta
Suresh Atta

Reputation: 122026

Keep in mind about type erasure. The Obvious answer is,

List<Class> myList = new ArrayList<Class>(); 

You can only specify the type of Object (for compiler). You can't see them at Run Time :)

Upvotes: 1

You can't use variable name as the type. You must use Class instead of clazz

List<Class> myList = new ArrayList<Class>(); 

Upvotes: 1

Related Questions