Java泛型 - 检索类型 [英] Java generics - retrieve type

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

问题描述

public Interface Foo<T extends Colors>{...}

有没有一种方法可以检索Foo实现的T?

Is there a way to retrieve which T was given for an implementation of Foo?

例如,

For example,

public Class FooImpl implements Foo<Green>{..}

会返回绿色。

推荐答案

与其他答案相反,您可以获取泛型参数的类型。例如,将此添加到泛型类中的方法将获得该类的第一个泛型参数(在您的情况下为 T ):

Contrary to other answers, you can obtain the type of a generic parameter. For example, adding this to a method inside a generic class will obtain the first generic parameter of the class (T in your case):

ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
type.getActualTypeArguments()[0]

我在通用的Hibernate DAO中使用这种技术我写了这样我可以获得持久化的实际类,因为它是Hibernate所需要的。它的工作原理!

I use this technique in a generic Hibernate DAO I wrote so I can obtain the actual class being persisted because it is needed by Hibernate. It works!

这篇关于Java泛型 - 检索类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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