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

泛型对象可以实例化吗?

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

9c6119699599f7cfca12dad8c2393644.png

解决方法

使用反射新建实例

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

}

}

执行结果

8bc3bb3d046e798aca627c807c4a7c48.png

控制台输出

fa1f1d133fe5fe3747b90c29911a9a0a.png

完整代码

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

'}';

}

}

相关文章

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值