泛型对象可以实例化吗?

不可以,T t=new T()是不可以的,编译器会报错。由于泛型擦除,编译器在编译时无法确定泛型所对应的真实类型

 Java泛型实例化

解决方法

使用反射新建实例

Type superclass = getClass().getGenericSuperclass();
ParameterizedType parameterizedType = null;
if (superclass instanceof ParameterizedType) {
   parameterizedType = (ParameterizedType) superclass;
   Type[] typeArray = parameterizedType.getActualTypeArguments();
   if (typeArray != null && typeArray.length > 0) {
      clazz = (Class<T>) typeArray[0];
                
   }
}

 

执行结果

Java泛型实例化

控制台输出

 

Java泛型实例化

完整代码

package com.learn.genericinstance;


import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericInstanceLearn {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        UserDao userDao = new UserDao();
        System.out.println(userDao.toString());
    }
}


class Dao<T> {
    public Class<T> clazz;
    public T user;
    public Dao() throws IllegalAccessException, InstantiationException {
        Type superclass = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType = null;
        if (superclass instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) superclass;
            Type[] typeArray = parameterizedType.getActualTypeArguments();
            if (typeArray != null && typeArray.length > 0) {
                clazz = (Class<T>) typeArray[0];
                user= clazz.newInstance();
            }
        }
    }

    @Override
    public String toString() {
        return "Dao{" +
                "user=" + user.toString() +
                '}';
    }
}

class UserDao extends Dao<User> {

    public UserDao() throws IllegalAccessException, InstantiationException {
    }

    @Override
    public String toString() {
        return super.toString();
    }
}

class User {
    String name;

    public User() {
        this.name = "default name";
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2021-09-03
  • 2021-12-09
  • 2022-02-07
  • 2021-10-26
猜你喜欢
  • 2021-10-11
  • 2021-06-07
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案