且构网

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

在Java中创建T的新实例

更新时间:2023-12-03 20:19:04

不,你不能做新的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);
}