不需要将泛型作为输入参数的情况下,检索泛型类型的类实例。
创始人
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、we...
透视脚本!wepoker正确养... 透视脚本!wepoker正确养号方法,德普之星透视辅助软件是真的吗,窍门教程(竟然存在有挂)-哔哩哔...
透视好牌!wepoker高级辅... 透视好牌!wepoker高级辅助,789大菠萝插件功能,原来真的是有挂(专业解说技巧)-哔哩哔哩1)...
透视安卓版本!wpk德州局透视... 透视安卓版本!wpk德州局透视(透视)开挂辅助app(确实有挂)-哔哩哔哩1)wpk德州局透视辅助挂...
透视真的!hhpoker脚本下... 透视真的!hhpoker脚本下载,hh poker软件,手段教程(确实真的是有挂)-哔哩哔哩1、hh...
透视私人局!如何下载wepok... 透视私人局!如何下载wepoker安装包,手游挂机辅助免费版,好像真的有挂(必备介绍教程)-哔哩哔哩...
透视小程序!aapoker辅助... 透视小程序!aapoker辅助工具安全吗(透视)开挂辅助插件(本来是真的挂)-哔哩哔哩1、超多福利:...
透视app!hhpoker可以... 透视app!hhpoker可以控制牌吗,德普之星app安卓版破解版,妙计教程(真是真的是有挂)-哔哩...
透视有挂!wpk免费辅助,江西... 透视有挂!wpk免费辅助,江西中至黑科技辅助插件,其实是真的挂(关于第三方教程)-哔哩哔哩进入游戏-...
透视插件!wepoker免费辅... 透视插件!wepoker免费辅助器(透视)开挂辅助软件(果然真的是有挂)-哔哩哔哩进入游戏-大厅左侧...