0
我想通了,动态调用默认方法的方法如下:Java反射调用默认的方法从以前的帖子
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);
这工作完全正常;但是,如果调用来自覆盖特定方法的派生接口,那么上面的代码将调用基接口的方法。
所以,问题是在基本接口上有一个默认方法,比方说'void fire()',并且子接口覆盖了这个方法,那么调用默认方法的机制,调用总是只有基类中的一个。
第一行的*方法来自哪里? – waltersu
@waltersu它是调用处理程序的'invoke'方法的参数。上面的代码在调用处理程序中。 –