samedi 11 juin 2016

Java reflection call default method from derived class

from previous posts I figured out that the way to dynamically call a default method is the following:

final Class<?> declaringClass = method.getDeclaringClass();

final Constructor<Lookup> constructor =  
MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);

constructor.setAccessible(true);

final MethodHandles.Lookup defaultMethodLookup =
                constructor.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE);

return defaultMethodLookup
            .unreflectSpecial(method, declaringClass)
            .bindTo(proxy)
            .invokeWithArguments(args);

This works perfectly fine; however, if the call is from a derived interface which overrides the specific method, then the code above invokes the method of the base interface.

So, the problem is in the case that there is a default method on a base interface, let say ‘void fire()’, and a sub interface overrides this method, then the mechanism that invokes the default methods, invokes always only the one on the base class.





Aucun commentaire:

Enregistrer un commentaire