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

相关内容

热门资讯

透视法子!约局吧游戏挂(透视)... 透视法子!约局吧游戏挂(透视)xpoker辅助助手(辅助)总是是有攻略(哔哩哔哩)1、约局吧游戏挂脚...
透视办法!竞技联盟透视插件(A... 透视办法!竞技联盟透视插件(AApoker辅助)果然真的是有辅助攻略(哔哩哔哩)1、实时竞技联盟透视...
透视操作!sohoo开挂辅助(... 透视操作!sohoo开挂辅助(透视)约局吧透视挂下载(辅助)总是一直总是有脚本(哔哩哔哩)约局吧透视...
透视资料!德州局透视脚本(透视... 透视资料!德州局透视脚本(透视)菠萝德普辅助器免费版在哪里(辅助)确实真的是有脚本(哔哩哔哩)该软件...
透视课程!aapoker怎么拿... 透视课程!aapoker怎么拿好牌(HHpoker工具)总是真的是有辅助app(哔哩哔哩)1、点击下...
透视讲义!wejoker辅助器... 透视讲义!wejoker辅助器要钱玩吗(WPK方法)竟然存在有辅助脚本(哔哩哔哩)1、wejoker...
透视经验!hhpkoer辅助挂... 透视经验!hhpkoer辅助挂是真的吗(德普之星透视)其实真的是有辅助方法(哔哩哔哩)在进入hhpk...
透视大纲!pokemmo辅助脚... 透视大纲!pokemmo辅助脚本(透视)哈糖大菠萝怎么开挂(辅助)竟然有方法(哔哩哔哩)1)哈糖大菠...
透视手筋!pokemmo手机版... 透视手筋!pokemmo手机版脚本(透视)大菠萝789辅助器下载(辅助)总是是有神器(哔哩哔哩)1)...
透视资料!约局吧德州真的有透视... 透视资料!约局吧德州真的有透视挂吗(透视)智星菠萝透视(辅助)都是真的是有app(哔哩哔哩)1、很好...