不需要将泛型作为输入参数的情况下,检索泛型类型的类实例。
创始人
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 类型的实例。

相关内容

热门资讯

必备科技!拱趴大菠萝有挂吗,德... 您好,拱趴大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
一分钟了解!德州私人局怎么透视... 一分钟了解!德州私人局怎么透视,pokemmo手机脚本,2025新版教程(有挂透视);原来确实真的有...
一分钟揭秘!哈糖大菠萝开挂,h... 一分钟揭秘!哈糖大菠萝开挂,hhpoker作弊码,必胜教程(有挂技巧);1.哈糖大菠萝开挂 ai辅助...
今日公布!哈糖大菠萝可以开挂吗... 今日公布!哈糖大菠萝可以开挂吗,wepoker怎么看底牌,详细教程(有挂方法)是由北京得哈糖大菠萝可...
玩家攻略!哈糖大菠萝有挂吗,佛... 玩家攻略!哈糖大菠萝有挂吗,佛手在线大菠萝智能辅助器,2025新版技巧(有挂软件);1分钟了解详细教...
最新技巧!模拟器打开hhpok... 最新技巧!模拟器打开hhpoker,wpk官网下载链接,我来教教你(有挂方法);模拟器打开hhpok...
一分钟揭秘!pokemmo脚本... 一分钟揭秘!pokemmo脚本,hhpoker脚本,微扑克教程(有挂技巧);建议优先通过pokemm...
安装程序教程!德普之星辅助器怎... 安装程序教程!德普之星辅助器怎么用,wepoker辅助器怎么弄,微扑克教程(有挂透明)1、不需要AI...
记者发布!wepoker黑侠辅... 1、记者发布!wepoker黑侠辅助器正版下载,wejoker黑侠辅助器,高科技教程(有挂教程)。2...
实测教程!wepoker插件辅... 实测教程!wepoker插件辅助,wepoker有辅助功能吗,软件教程(有挂攻略)关于wepoker...