如何获取参数化的类实例 [英] How to get parametrized Class instance

查看:120
本文介绍了如何获取参数化的类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于引入了泛型,因此Class是参数化的,因此List.class会生成Class< List> ;.这是很清楚的。



我无法弄清楚如何获得参数化类型的Class实例,即Class< List< String >> 。像这样的代码片段:

  public class GenTest {
static< T> T实例化(Class< T> clazz)抛出Exception {
return clazz.newInstance();
}
public static void main(String [] args)throws Exception {
//有没有办法避免
下面的行不要使用@SuppressWarnings( 未登记)?
// ArrayList.class是Class< ArrayList>,但是我想
//传入Class< ArrayList< String>>
ArrayList< String> l = GenTest.instantiate(ArrayList.class);


$ / code $ / pre

我经常碰到这个问题的变化,仍然不知道,如果我只是想念什么,或者如果真的没有更好的办法。感谢您的建议。

解决方案

Class类是类型的运行时表示。由于参数化类型在运行时进行了类型擦除,所以Class的类对象将与Class< List< Integer>和Class< List< String>相同。 >您无法使用.class表示法实例化它们的原因是,这是用于类文字的特殊语法。 Java语言规范特别禁止此操作当参数类型为参数时,这就是为什么List< String> .class不被允许的原因。


Since generics were introduced, Class is parametrized, so that List.class produces Class<List>. This is clear.

What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class<List<String>>. Like in this snippet:

public class GenTest {
    static <T> T instantiate(Class<T> clazz) throws Exception {
        return clazz.newInstance();
    }
    public static void main(String[] args) throws Exception {
        // Is there a way to avoid waring on the line below
        // without using  @SuppressWarnings("unchecked")?
        // ArrayList.class is Class<ArrayList>, but I would like to
        // pass in Class<ArrayList<String>>
        ArrayList<String> l = GenTest.instantiate(ArrayList.class);
    }
}

I run into variations of this problem quite often and I still don't know, if I just miss something, or if there is really no better way. Thanks for suggestions.

解决方案

The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class object for Class would be the same as for Class<List<Integer>> and Class<List<String>>.

The reason you cannot instantiate them using the .class notation is that this is a special syntax used for class literals. The Java Language Specification specifically forbids this syntax when the type is parametrized, which is why List<String>.class is not allowed.

这篇关于如何获取参数化的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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