不需要将泛型作为输入参数的情况下,检索泛型类型的类实例。
创始人
2025-01-10 13:30:30
0

要检索泛型类型的类实例,可以使用Java的反射机制。通过反射,可以获取类的泛型类型,并实例化该泛型类型的对象。下面是一个示例代码:

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

public class GenericClass {
    private Class type;

    public GenericClass() {
        // 获取泛型类型
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments != null && actualTypeArguments.length > 0) {
                type = (Class) actualTypeArguments[0];
            }
        }
    }

    public T createInstance() throws IllegalAccessException, InstantiationException {
        // 实例化泛型类型的对象
        return type.newInstance();
    }
}

使用上述代码,可以通过以下方式检索泛型类型的类实例:

public class MyClass {
    public static void main(String[] args) {
        GenericClass generic = new GenericClass() {};
        try {
            String instance = generic.createInstance();
            System.out.println(instance);
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,GenericClass 是一个泛型类,通过反射获取泛型类型 T,并使用 newInstance() 方法实例化泛型类型的对象。在 MyClass 中,通过实例化 GenericClass,可以获得一个 String 类型的实例。

相关内容

热门资讯

开挂辅助工具"拱趴大... 开挂辅助工具"拱趴大菠萝自动计算机器人"开挂(透视)辅助插件(有挂方式);无需打开直接搜索加薇136...
开挂辅助工具"哈糖大... 开挂辅助工具"哈糖大菠萝有没有挂"开挂(透视)辅助下载(有挂讲解);无需打开直接搜索微信(13670...
开挂辅助安装"wep... 开挂辅助安装"wepoker插件程序激活码"开挂(透视)辅助神器(有挂技巧)>>您好:软件加1367...
开挂辅助下载"wep... 开挂辅助下载"wepoker有没有挂"开挂(透视)辅助工具(有挂秘籍)【无需打开直接搜索加薇1367...
开挂辅助工具"hhp... 开挂辅助工具"hhpoker有没有辅助"开挂(透视)辅助下载(有挂分析)hhpoker有没有辅助ai...
开挂辅助插件"wep... 开挂辅助插件"wepoker透视脚本"开挂(透视)辅助软件(有挂技术);打开点击测试直接进入微信(1...
开挂辅助安装"约局吧... 开挂辅助安装"约局吧透视挂下载"开挂(透视)辅助工具(了解有挂)>>您好:软件加薇136704302...
开挂辅助脚本"wep... 开挂辅助脚本"wepoker怎么设置透视"开挂(透视)辅助插件(有挂教程)>>您好:软件加13670...
开挂辅助下载"大菠萝... >>您好:大菠萝免费辅助器确实是有挂的,很多玩家在这款大菠萝免费辅助器游戏中打牌都会发现很多用户的牌...
开挂辅助软件"约局吧... 大家好,今天小编来为大家解答约局吧透视挂下载这个问题咨询软件客服可以免费测试直接加微信(136704...