且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中创建的T新实例

更新时间:2023-12-03 20:31:35

没有你不能做新的T(),因为你不知道T是否有一个没有arg构造函数,由于类型删除,T的类型在运行时不存在。

No you can't do new T(), since you don't know if T has a no arg constructor, and because the type of T is not present at runtime due to type erasure.

要创建T的实例,您需要具有

To create an instance of T, you need to have code like,

public <T> T create(Class<T> clazz) {
    try {
        //T must have a no arg constructor for this to work 
        return clazz.newInstance(); 
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
}