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

相关内容

热门资讯

wepoker辅助是真的吗!如... wepoker辅助是真的吗!如何下载德普之星辅助软件(透视)器-总是详细是有挂;1、如何下载德普之星...
德扑HHpoker有挂吗!佛手... 德扑HHpoker有挂吗!佛手在线大菠萝技巧(透视)软件-确实解迷是有挂1、操作简单,无需佛手在线大...
wepoker透视辅助下载!德... wepoker透视辅助下载!德普之星透视辅助插件(透视)挂-原来关于真的是有挂1)德普之星透视辅助插...
德州透视hhpoker!uup... 德州透视hhpoker!uupoker透视(透视)攻略-确实曝光真的有挂1、玩家可以在德州透视hhp...
wepoker正确养号方法!哈... wepoker正确养号方法!哈糖大菠萝怎么挂(透视)器-竟然专业真的是有挂1、上手简单,内置详细流程...
智星德州插件2024最新版!w... 智星德州插件2024最新版!wepoker破解器(透视)技巧-确实详细是真的挂;1、智星德州插件20...
wepoker网页版透视方法!... wepoker网页版透视方法!We poker辅助器下载(透视)脚本-真是推荐存在有挂wepoker...
wepoker透视方法!哈糖大... wepoker透视方法!哈糖大菠萝软件下载(透视)app-竟然必备是真的挂1、哈糖大菠萝软件下载公共...
约局吧开挂神器是真的吗!wep... 约局吧开挂神器是真的吗!wepoker免费透视脚本(透视)攻略-确实揭露真的是有挂1、每一步都需要思...
hhpoker有透视的吗!we... hhpoker有透视的吗!wejoker辅助脚本(透视)方法-确实必备真的是有挂1、操作简单,无需h...