How to get the actual type arguments to an indirectly implemented generic interface?

后端 未结 3 1465
时光说笑
时光说笑 2021-02-09 08:40

I have a parameterized interface that is implemented in many different ways. At run time I need to figure out, given an arbitrary object that implements that interface, what the

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-09 09:01

    Following proposal of @oconnor0, here is how to do it with gentyref:

    static Type investigate(Awesome somethingAwesome) {
        return GenericTypeReflector.getTypeParameter(somethingAwesome.getClass(), Awesome.class.getTypeParameters()[0]);
    }
    

    In case somethingAwesome.getClass() could be also generic, it might be useful to pass it through GenericTypeReflector.addWildcardParameters first.

    Spring has also a GenericTypeResolver.resolveTypeArgument(Class,Class) which can achieve the same result.

提交回复
热议问题