从超类型类中获取泛型参数 [英] Getting generic parameter from supertype class

查看:90
本文介绍了从超类型类中获取泛型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的父接口/类

Say I have a parent interface/class like so

interface Parent<T> {}

以及许多修复泛型类型的实现接口。

And a number of implementing interfaces that fix the generic type.

interface Child extends Parent<Type> {}

我可以使用反射来获取 Class 代表 T 如果我有 Class 对象。这样的事情:

Can I use reflection to get the instance of Class representing T if I have the Class object for Child. Something like this:

<T, I extends Parent<T>> I create(Class<I> type) {
    Class<T> tType = ...
    ...
}

目前我是将 tType 作为参数传入,但如果可以,我想简化一些事情。

Currently I'm having tType be passed in as a parameter, but I'd like to simplify things if I can.

推荐答案

是的,尽管其他人已经说过,如果您有权访问子类' Class 可用>对象。您需要使用 getGenericSuperclass 以及 getActualTypeArguments

Yes, despite what the others have said, this info is available if you have access to the subclass' Class object. You need to use getGenericSuperclass along with getActualTypeArguments.

ParameterizedType superClass = (ParameterizedType)childClass.getGenericSuperclass();
System.out.println(superClass.getActualTypeArguments()[0]);

在您的示例中,actual类型参数应返回 Class for 输入

In your example, the "actual" type argument should return the Class for Type.

这篇关于从超类型类中获取泛型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆