简体   繁体   English

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

[英]How to get concrete type of a generic interface

I have an interface 我有一个界面

public interface FooBar<T> { }

I have a class that implements it 我有一个实现它的类

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 .getInterfaces from BarFoo to get back to FooBar, but that doesn't help me find out what T is. 我使用.getInterfaces的.getInterfaces来回到FooBar,但这并不能帮助我找出T是什么。

You can grab generic interfaces of a class by Class#getGenericInterfaces() which you then in turn check if it's a ParameterizedType and then grab the actual type arguments accordingly. 您可以通过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);
        }
    }
}

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];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java - 如何在覆盖泛型类型的接口方法时获取具体参数类型 - Java - How to get concrete parameter type when overriding interface method of generic type Java反思:获取已实现通用接口的具体类型 - Java reflection: Get concrete type of implemented generic interface 如何在实现通用接口时返回具体类型 - How to return a concrete type when implementing a generic interface 如何获取从具有指定泛型(接口)的接口继承的所有类的列表<concrete class> )</concrete> - How get list of all classes that inherit from the interface with the specified generic (interface<concrete class>) 如何在Java中将泛型转换为具体类型 - How to convert a generic type to a concrete type in Java 如何在Java中获取通用接口的类型 - How to get type of generic interface in java 如何在Clojure中使用具体类型参数实现接口? - How to implement an interface with concrete type parameters in Clojure? 你能指定一个泛型类型,它继承另一个泛型类型_and_具体的接口吗? - Can you specify a generic type that subclasses another generic type _and_ a concrete interface? 当接口方法的泛型返回使用 Java 中的具体类型实现时,如何避免“未检查覆盖”警告? - How can I avoid an "Unchecked overriding" warning when interface method's generic return is implemented with a concrete type in Java? 如何获取间接实现的通用接口的实际类型参数? - How to get the actual type arguments to an indirectly implemented generic interface?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM