How to get concrete type of a generic interface

前端 未结 2 572
北荒
北荒 2020-12-28 17:08

I have an interface

public interface FooBar { }

I have a class that implements it

public class BarFoo implements Foo

相关标签:
2条回答
  • 2020-12-28 17:55

    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.

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-28 18:01

    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];
    }
    
    0 讨论(0)
提交回复
热议问题