亲宝软件园·资讯

展开

Java泛型实例化 Java让泛型实例化的方法

夜空中最亮的盖子 人气:3

泛型对象可以实例化吗?

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

解决方法

使用反射新建实例

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];
        
  }
}

执行结果

控制台输出

完整代码

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 + '\'' +
        '}';
  }
}

加载全部内容

相关教程
猜你喜欢
用户评论