不需要将泛型作为输入参数的情况下,检索泛型类型的类实例。
创始人
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】很多玩家在这款游...
热门推荐!aapoker免费透... 1、热门推荐!aapoker免费透视脚本,wepoker有辅助吗,揭秘教程(有挂技巧)(UU pok...
透视游戏"xpoke... 透视游戏"xpoker辅助"详细辅助揭秘教程(原本是有挂)是一款可以让一直输的玩家,快速成为一个“必...
技术分享!we poker免费... 技术分享!we poker免费辅助器,hhpoker可以开挂吗,实用技巧(有挂教程);玩家必备必赢加...
透视玄学"德普之星辅... 透视玄学"德普之星辅助器怎么用"详细辅助软件教程(一直真的是有挂)这是由厦门游乐互动科技有限公司精心...
一起来探讨!竞技联盟透视,we... 一起来探讨!竞技联盟透视,wepoker如何设置透视,分享教程(有挂神器)是一款可以让一直输的玩家,...
透视好友房"wejo... 透视好友房"wejoker手机版透视脚本"详细辅助详细教程(果然存在有挂);建议优先通过wejoke...
推荐十款!哈糖大菠萝有没有挂,... 推荐十款!哈糖大菠萝有没有挂,wepoker免费透视脚本,透明挂教程(有挂技巧)是一款可以让一直输的...
透视脚本"pokem... 透视脚本"pokemmo手机版修改器"详细辅助曝光教程(最初真的有挂)准备好在pokemmo手机版修...
最新技巧!pokemmo手机版... 最新技巧!pokemmo手机版脚本免费,wepoker私人局辅助,细节方法(有挂透明);实战中需综合...