Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying a generic type in java from Class object

Why this is wrong:

    Class<? extends Number> type = Integer.class;
    ArrayList<type> = new ArrayList<>();

?

Is there no way to instantiate a class of a specific type given a class object?


Obviously I would never do that directly, that is just an example to show what is needed. In the actual code I need I don't know the name of the type. For example

    public void createAList(Class<? extends Number> type)  
{
    ArrayList<type> toReturn = new ArrayList<>();
    return toReturn;
}
like image 405
CarrKnight Avatar asked Mar 07 '13 19:03

CarrKnight


People also ask

How do you declare a generic type in a class explain?

The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas.

How do you pass a generic Object in Java?

Generics Work Only with Reference Types: When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);

How do you initialize a generic type in Java?

If you want to initialize Generic object, you need to pass Class<T> object to Java which helps Java to create generic object at runtime by using Java Reflection.


1 Answers

<T extends Number> ArrayList<T> createAList(Class<T> type)  
{
    ArrayList<T> toReturn = new ArrayList<>();
    return toReturn;
}


ArrayList<Integer> intList = createAList(Integer.class);
like image 72
irreputable Avatar answered Oct 16 '22 08:10

irreputable