如何获得通用接口的具体类型 [英] How to get concrete type of a generic interface

查看:65
本文介绍了如何获得通用接口的具体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个界面

public interface FooBar<T> { }

我有一个实现它的类

公共类BarFoo实现了FooBar< Person> {}

通过反射,我想获取一个BarFoo实例并得到它实现的FooBar版本是Person。

With reflection, I want to take an instance of BarFoo and get that the version of FooBar it implements is Person.

我使用BarFoo的 .getInterfaces 来回到FooBar,但这并没有帮我找出T是什么。

I use .getInterfaces from BarFoo to get back to FooBar, but that doesn't help me find out what T is.

推荐答案

您可以通过 Class#getGenericInterfaces() 然后你检查它是否是 ParameterizedType 然后获取相应的实际类型参数

Type[] genericInterfaces = BarFoo.class.getGenericInterfaces();
for (Type genericInterface : genericInterfaces) {
    if (genericInterface instanceof ParameterizedType) {
        Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();
        for (Type genericType : genericTypes) {
            System.out.println("Generic type: " + genericType);
        }
    }
}

这篇关于如何获得通用接口的具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆