java 如何获得通用接口的具体类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3247058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:58:57  来源:igfitidea点击:

How to get concrete type of a generic interface

javareflection

提问by bwawok

I have an interface

我有一个界面

public interface FooBar<T> { }

I have a class that implements it

我有一个实现它的类

public class BarFoo implements FooBar<Person> { }

public class BarFoo implements FooBar<Person> { }

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

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

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

我使用.getInterfacesfrom BarFoo 返回到 FooBar,但这并不能帮助我找出 T 是什么。

回答by BalusC

You can grab generic interfaces of a class by Class#getGenericInterfaces()which you then in turn check if it's a ParameterizedTypeand then grab the actual type argumentsaccordingly.

您可以获取类的泛型接口,Class#getGenericInterfaces()然后依次检查它是否为 a 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);
        }
    }
}

回答by matt b

Try something like the following:

请尝试以下操作:

Class<T> thisClass = null;
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) type;
    Type[] typeArguments = parameterizedType.getActualTypeArguments();
    thisClass = (Class<T>) typeArguments[0];
}