Java让泛型实例化的方法
泛型对象可以实例化吗?
不可以,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 + '\'' +
'}';
}
}
以上是 Java让泛型实例化的方法 的全部内容, 来源链接: utcz.com/z/335904.html