泛型对象可以实例化吗?
不可以,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) 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 {
public Class 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) typeArray[0];
user= clazz.newInstance();
}
}
}
@Override
public String toString() {
return "Dao{" +
"user=" + user.toString() +
"}";
}
}
class UserDao extends Dao {
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让泛型实例化的方法的详细内容,更多关于Java泛型实例化的资料请关注云海天教程其它相关文章!
原文链接:https://www.cnblogs.com/billshen/p/13257770.html