Java反射:获取实现的通用接口的具体类型
假设我有一个如下所示的类
public class AtomEntryHandler implements ConsumingHandler<AtomEntry>
{
...
}
是否可以从 AtomEntryHandler.class 的类对象获取类对象 AtomEntry.class ?
我以为不可能,因为删除了,但朋友说可以。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以获得接口和直接子类的泛型类型,但仅限于具体实现。例如,如果您有一个
List
实例,则由于类型擦除,您无法知道它被参数化的内容。如果类定义包含编译时已知的参数化类型(例如,class StringList extends List
),那么您可以检索该信息。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.我无法找到一种方法来确定接口实现情况下的基本类型参数(这并不意味着没有)。但这已经很接近了。
结果:
类 java.lang.Integer
I could not figure a way to determine base type parameter in case of interface implementation (which does not mean there is none). But this is as close as it gets to it.
Result:
class java.lang.Integer
如果您碰巧知道
ConsumingHandler
是AtomEntryHandler
实现的唯一接口,并且您碰巧知道它只需要一个类型参数,您可以这样做:否则,您可以四处看看在
getGenericInterfaces()
及其actualTypeArguments
中,直到找到与您要查找的内容类似的内容。但是,如果您发现自己需要在实际代码中执行此操作,则要么您的设计中可能出现严重错误,要么您正在编写一些疯狂的天才模拟对象库,并且您不应该需要我们来回答这些问题。
If you happen to know
ConsumingHandler
is the only interfaceAtomEntryHandler
implements, and you happen to know it takes just one type argument, you can do this:Otherwise, you can poke around in
getGenericInterfaces()
and theiractualTypeArguments
until you find something that looks like what you're looking for.But if you find yourself needing to do this in real code, either something's probably gone badly wrong in your design, or you're writing some mad genius mock object library and you shouldn't need us to answer these questions.
这里有一篇博客文章详细介绍了它:
Reflecting Generics< /代码>
。
There is a blog post that goes over it in detail here:
Reflecting Generics
.