从Class对象指定Java中的泛型类型 [英] Specifying a generic type in java from Class object

查看:128
本文介绍了从Class对象指定Java中的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这是错误的:

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;
}


推荐答案

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


ArrayList<Integer> intList = createAList(Integer.class);

这篇关于从Class对象指定Java中的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆