3

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.

2
  • 2
    Use generics - public <T> List<T> getList(final T t). Commented Aug 12, 2014 at 14:12
  • Can you add a small example? Commented Aug 12, 2014 at 14:14

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is wrong. You can easily use a generic method to create a List of the appropriate type.
true, but then you still need to pass a type argument to the generic method somehow and you can't do that, only based on the class object. I'll clarify that in the answer
ok, i just checked it myself and you're totally right. When one uses the generic version of Class (Class<T>) then it works
1

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

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

Comments

1

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.