mardi 5 janvier 2016

Get parent method with fixed generic parameter by reflection

Let's have this class structure:

abstract class Event {}
class EventImpl extends Event {}

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

class FooImpl extends Foo<EventImpl> {
}

I'm trying to find by reflection the Method foo from a FooImpl instance. I suposed this should work:

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

However, I'm getting a NoSuchMethodException. It seems to be that the generic parameter T, fixed as EventImpl, cannot be recognized as a method parameter, because if I try to find the method in this way, is working fine:

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

Is normal this behaviour or I'm missing something here? Thanks for the help.

Just a basic test to help to reproduce the error:

@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
}





Aucun commentaire:

Enregistrer un commentaire