English 中文(简体)
• 如何从小化清单中产生新的通用型T物体
原标题:How to create new object of Generic Type T from a parametrized List<T>

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

它正在编制一份汇编性警报:

类型安全: 捕获量第1号中的未经控制的投放物? 有效期 反对T

如果我确实做到:

T obj = objects.get(i);

众所周知的是T型。

为什么我无法创建这一类的新例子? 我怎么能够确定?

(我不寻求对类型的答复): Add @Suppresswarnings(“unchecked”):

最佳回答

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.


但在此,许多申请和图书馆都这样做:

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();
    }
}
问题回答

普通课程在学期消失。 因此,在已申报的<代码>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);
    }
}

为什么我无法创建这一类的新例子?

你就是这样。 你的法典将汇编,并将按你的期望开展工作,但是,由于类型时代的原因,汇编者将掌握100%的保证。 这里需要指出的是,警告与错误并不相同。

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

If you look at any Java code base that uses generics and reflection in conjunction with each other, you will see suppressed warnings for type safety. That s just a fact of life, unfortunately.

有人说,你正在处理一种通用类型(<); 扩展范围:t>。 处理这一问题的另一个方式是使用as Subclass( on T.

E.g. 替换 表格

 Class<? extends T> myClass = null;
 myClass = [your class var].getClass().asSubclass(T.class);




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签