How to get concrete type of a generic interface

前端 未结 2 582
北荒
北荒 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 18:01

    Try something like the following:

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

提交回复
热议问题