Specifies the generic type in Java from the class object

Why is this wrong:

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

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

Obviously, I will never do this directly, just an example of what is needed In actual code, I need to know the name of the type I don't know for example

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

Solution

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


ArrayList<Integer> intList = createAList(Integer.class);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>