gpt4 book ai didi

java - 通过反射获取固定泛型参数的父方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:13 26 4
gpt4 key购买 nike

让我们有这样的类结构:

abstract class Event {}
class EventImpl extends Event {}

class Foo<T extends Event> {
public void foo(T event) {}
}

class FooImpl extends Foo<EventImpl> {
}

我试图通过反射从 FooImpl 实例中找到 Method foo。我认为这应该有效:

FooImpl fooImpl = new FooImpl();
Class clazz = fooImpl.getClass();
Method foo = clazz.getMethod("foo", EventImpl.class);

但是,我得到了一个 NoSuchMethodException。似乎是固定为 EventImpl 的通用参数 T 无法识别为方法参数,因为如果我尝试以这种方式找到方法,则可以正常工作很好:

Method fooParent = clazz.getMethod("foo", Event.class);

这种行为是正常的还是我遗漏了什么?感谢您的帮助。

只是帮助重现错误的基本测试:

@Test
public void test() throws Exception {
FooImpl fooImpl = new FooImpl();
// Method foo of class FooImpl need to be called with parameter EventImpl
fooImpl.foo(new EventImpl());

Class clazz = fooImpl.getClass();
Method fooParent = clazz.getMethod("foo", Event.class); // OK
Method foo = clazz.getMethod("foo", EventImpl.class); // NoSuchMethodException
}

最佳答案

这是由于 type erasure 属于泛型

来自 Oracle 文档:

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

由于Reflection是一种运行时现象,由于泛型的类型删除,foo的参数被替换为Event(由于绑定(bind)通过 T extends Event)。

因此,您必须将 Event.class 作为参数传递。

关于java - 通过反射获取固定泛型参数的父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com