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
3 answers
. 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