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

相关内容

热门资讯

透视神器!hhpoker德州透... 透视神器!hhpoker德州透视,We poker辅助器下载,法子教程(一贯真的是有挂)-哔哩哔哩1...
透视线上!wepoker游戏的... 透视线上!wepoker游戏的安装教程(透视)开挂辅助技巧(真是有挂)-哔哩哔哩1、很好的工具软件,...
透视代打!werplan外卦神... 透视代打!werplan外卦神器,德普辅助器怎么用,模板教程(都是真的有挂)-哔哩哔哩1、每一步都需...
透视苹果!拱趴大菠萝有挂吗(透... 透视苹果!拱趴大菠萝有挂吗(透视)开挂辅助器(本来真的是有挂)-哔哩哔哩1、拱趴大菠萝有挂吗透视辅助...
透视真的!wepoker软件辅... 透视真的!wepoker软件辅助程序,wepoker辅助脚本,指南教程(都是存在有挂)-哔哩哔哩1、...
透视计算器!hhpoker俱乐... 透视计算器!hhpoker俱乐部是干嘛的(透视)开挂辅助软件(其实有挂)-哔哩哔哩1、起透看视 hh...
透视新版!wpk俱乐部辅助器,... 透视新版!wpk俱乐部辅助器,pokemmo脚本最新版,手筋教程(确实真的是有挂)-哔哩哔哩1、po...
透视必胜!wepoker模拟器... 透视必胜!wepoker模拟器哪个好用(透视)开挂辅助插件(确实是有挂)-哔哩哔哩1、操作简单,无需...
透视好友房!hhpoker可以... 透视好友房!hhpoker可以控制吗,德普之星透视,阶段教程(都是真的是有挂)-哔哩哔哩1、这是跨平...
透视俱乐部!hhpoker怎么... 透视俱乐部!hhpoker怎么防辅助(透视)开挂辅助软件(总是存在有挂)-哔哩哔哩一、hhpoker...