3

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;}
}
1
  • Is this to avoid having to write out new ArrayList<Vo>() whenever you need a list of Vo? Otherwise I dont see what you could possibly gain from this. Commented Mar 16, 2015 at 19:57

2 Answers 2

3

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.

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

Comments

1

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.

1 Comment

thanks for your answer. I'm still trying to wrap my head around generics. This was more of a hypothetical question, to try and better understand generics.

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.