普通课程在学期消失。 因此,在已申报的<代码>t/code>上援引getClass(
>。 名单内容见<代码><? 有效期 对象;类。
。
The actual result type is Class<? extends |X|>
where |X|
is the
erasure of the static type of the expression on which getClass is
called.
To invoke newInstance()
and create an instance of T
you need to know the Class
instance which you want to instantiate but note that the List
can contain any subclass of T
, so passing a class as parameter may not be enough.
例如:
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);
No one as anyone will compile ! So it is clearly not enough.
So I think that it makes more sense to keep your original code by suppressing the warning. In this way you ensure that you will create an instance of the same class that the actual element in the list :
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);
}
}