How to create a new Generic Type T object from a parameterized list <T>

I have the following sample Java 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 issues a compiler warning:

Security Type: unchecked capture # 1-of? extends Object to T

I can perfectly get the exact T object if I just do:

T obj = objects.get(i);

What he knows perfectly is Type T.

Why can't I create a new instance of this class? How can i fix this?

(I'm not looking for an answer like: 'Add @SuppressWarnings ("unchecked")')

+4
source share
3 answers

, getClass() Class<? extends Object>. () ? , . Java Generics. , , .


: :

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

. getClass() T <? extends Object>.

Object.getClass():

Class<? extends |X|>, |X| - , getClass .

newInstance() T, Class, , , List T, .

:

List<Animal> list = new ArrayList<>();
list.add(new Lion());
list.add(new Rabbit());
list.add(new Turtle());

?

method(list, Lion.class); 
method(list, Rabbit.class);
method(list, Turtle.class);

, -! , . , , . , , , :

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
        @SuppressWarnings("unchecked")
        T obj = (T) objects.get(i).getClass().newInstance();
        System.out.println(obj);
    }
}
+2

?

. , , , 100% - , . , .

( : ' @SuppressWarnings ( "unchecked" )')

If you look at any Java code base that uses generalizations and reflection in combination with each other, you will see suppressed type safety warnings. This, unfortunately, is a fact of life.

+1
source

Source: https://habr.com/ru/post/1696350/


All Articles