简体   繁体   中英

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? I understand I can use ArrayList.class.newInstance() to create a new instance, but I can't pass in a type parameter. I want to do new ArrayList<String> , but instead of for that specific example, any class that has a type parameter.

Specifically, I am trying to implement testing of different implementations of an interface , through subclassing of a JUnit test.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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