不需要将泛型作为输入参数的情况下,检索泛型类型的类实例。
创始人
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软件可以玩吗,微乐小程序辅助器,积累教程(有挂头条)-哔哩哔哩1、hhpok...
关于透视!hhpoker开挂教... 您好,hhpoker开挂教程这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】...
详情透视!werplan怎么作... 详情透视!werplan怎么作弊,微乐自建房脚本入口,烘培教程(真实有挂)-哔哩哔哩1、下载好wer...
推荐透视!wepoker有辅助... 推荐透视!wepoker有辅助插件吗,微乐自建房辅助下载,讲义教程(有挂教程)-哔哩哔哩wepoke...
详细透视!wpk德州局透视,微... 详细透视!wpk德州局透视,微乐陕西小程序脚本,指南教程(果真有挂)-哔哩哔哩一、wpk德州局透视游...
辅助透视!hhpoker作弊码... 辅助透视!hhpoker作弊码怎么用,微乐小程序怎么挂脚本,技法教程(真的有挂)-哔哩哔哩hhpok...
了解透视!wepoker辅助器... 了解透视!wepoker辅助器如何使用,微信微乐小程序修改器,手册教程(有挂秘籍)-哔哩哔哩1、玩家...
了解透视!wepoker代打辅... 了解透视!wepoker代打辅助,微乐家乡脚本助手,经验教程(有挂秘笈)-哔哩哔哩在进入wepoke...
揭幕透视!wepoker透视功... 揭幕透视!wepoker透视功能下载,微信小程序微乐辅助器教程,手筋教程(真的有挂)-哔哩哔哩1、操...
教你透视!菠萝辅助器免费版的特... 教你透视!菠萝辅助器免费版的特点,微乐自建房辅助工具,总结教程(竟然有挂)-哔哩哔哩菠萝辅助器免费版...