简体   繁体   English

Java从类构造通用实例

[英]Java Construct Generic Instance From Class

I am trying to construct an instance of a generic class, with a type parameter. 我正在尝试使用类型参数构造泛型类的实例。 For example if have ArrayList.class and I want to initialize it with class String.class , how do I do that? 例如,如果有ArrayList.class而我想用String.class类对其进行初始化,该怎么办? I understand I can use ArrayList.class.newInstance() to create a new instance, but I can't pass in a type parameter. 我知道我可以使用ArrayList.class.newInstance()创建一个新实例,但是不能传递类型参数。 I want to do new ArrayList<String> , but instead of for that specific example, any class that has a type parameter. 我想做new ArrayList<String> ,但是对于那个特定的示例,不是任何具有类型参数的类。

Specifically, I am trying to implement testing of different implementations of an interface , through subclassing of a JUnit test. 具体来说,我正在尝试通过JUnit测试的子类化来实现对接口的不同实现的测试。

I realized that can just return an initialization of the generic class, without the type paremeter and just cast it to that paremeter. 我意识到,可以只返回泛型类的初始化,而无需使用类型参数,而是将其强制转换为该参数。

For example: 例如:

private Class<? extends List> implementation = ArrayList.class;

private <E> List<E> newList(Class<E> itemClass) {
    try {
        return (List)implementation.newInstance();
    } catch (Throwable x) {
       return null;
    }
}

@Test
public void test1() {
    List<String> testInstance = newList(String.class);
    testInstance.add('hey');
    assertEquals(3, testInstance.get(0).lenght());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM