Java反射:获取实现的通用接口的具体类型 [英] Java reflection: Get concrete type of implemented generic interface

查看:108
本文介绍了Java反射:获取实现的通用接口的具体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class AtomEntryHandler implements ConsumingHandler< AtomEntry> 
{
...
}

是否有可能从AtomEntryHandler.class类对象中获取类对象AtomEntry.class?



我不认为这是可能的,因为擦除,但有朋友说这是可能的。

解决方案

您可以获取接口和直接子类的泛型类型,但仅限具体实现。例如,如果你有一个 List< T> 实例,你无法知道它由于类型擦除而被参数化了。如果类定义包含编译时已知的参数化类型(例如, class StringList extends List< String> ),那么您可以 检索信息。

  ParameterizedType pt =(ParameterizedType)AtomEntryHandler.class.getGenericInterfaces()[0]; 
类atomEntryClass =(Class)pt.getActualTypeArguments()[0];


Say I have a class like the following

public class AtomEntryHandler implements ConsumingHandler<AtomEntry>
{
...
}

Is it possible to get the class object AtomEntry.class from the class object of AtomEntryHandler.class ?

I didn't think it was possible due to erasure, but a friend said it is.

解决方案

You can get the generic type for both interfaces and direct subclasses, but only for the concrete implementation. For example, if you have a List<T> instance, you have no way of knowing what it's been parameterized to because of type erasure. If the class definition includes parameterized types that are known at compile time (for example, class StringList extends List<String>) then you can retrieve that information.

ParameterizedType pt = (ParameterizedType)AtomEntryHandler.class.getGenericInterfaces()[0];
Class atomEntryClass = (Class)pt.getActualTypeArguments()[0];

这篇关于Java反射:获取实现的通用接口的具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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