让我们有这样的阶级结构:反射
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
找到。我suposed这应该工作:
FooImpl fooImpl = new FooImpl();
Class clazz = fooImpl.getClass();
Method foo = clazz.getMethod("foo", EventImpl.class);
但是,我得到一个NoSuchMethodException
。这似乎是泛型参数T
,固定为EventImpl
,不能被识别为方法的参数,因为如果我试图找到这样的方法,工作正常:
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
}
您没有重写类“FooImpl”中的方法。通过这样做,你的测试会通过。 – Seelenvirtuose
感谢您的评论。其实这是我的临时解决方案,但我认为这可能是其他选择。 – troig