How to create new object of Generic Type T from a parametrized List<T>

Mayday :

I have following java sample class:

public class TestClass {

    public static <T> void method(List<T> objects) throws Exception {
        for (int i = 0; i < objects.size(); i++) {
            // Create new object of the same class
            T obj = (T) objects.get(i).getClass().newInstance();
        }
    }
}

It is producing a compiler warning:

Type safety: Unchecked cast from capture#1-of ? extends Object to T

I can perfectly obtain the exact T object, if I just do:

T obj = objects.get(i);

Which it knows perfectly is of Type T.

Why I am not able to create a new instance of that class? How could I fix it?

(I am not looking for a response of type: 'Add @SuppressWarnings("unchecked")')

Impulse The Fox :

This happens because getClass() returns a Class<? extends Object>. You cannot (safely) cast the wildcard ? to anything, not even a generic class type. This is a limitation of Java Generics. But since you can be sure this warning is not a problem you can safely ignore or suppress it.


But here is a workaround, many applications and libraries do this:

public static <T> void method(List<T> objects, Class<T> clazz) throws Exception {
    for (int i = 0; i < objects.size(); i++) {
        // Create new object of the same class
        T obj = clazz.newInstance();
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474183&siteId=1