【发布时间】:2019-04-02 10:34:17
【问题描述】:
我想用 InvocationHandler 调用接口的默认方法。
我有这个代码。
public interface Calculator {
default int methodA(int a, int b) {
return a - b;
}
}
public class CalculatorInvocation implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return MethodHandles.lookup()
.in(method.getDeclaringClass())
.unreflectSpecial(method, method.getDeclaringClass())
.bindTo(this)
.invokeWithArguments();
}
}
public abstract class MainClass extends CalculatorInvocation {
public static void main(String[] args) {
InvocationHandler invocationHandler = new CalculatorInvocation();
Calculator c = (Calculator) Proxy.newProxyInstance(Calculator.class.getClassLoader(),new Class[]{Calculator.class},invocationHandler);
System.out.println(c.methodA(1, 3));
}
}
我只找到了一个 default method reflection 的例子。
更新:
我收到此错误:
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy0.methodA(Unknown Source)
at ir.moke.MainClass.main(MainClass.java:10)
Caused by: java.lang.IllegalAccessException: no private access for invokespecial: interface ir.moke.Calculator, from ir.moke.Calculator/package
at java.lang.invoke.MemberName.makeAccessException(MemberName.java:850)
at java.lang.invoke.MethodHandles$Lookup.checkSpecialCaller(MethodHandles.java:1572)
at java.lang.invoke.MethodHandles$Lookup.unreflectSpecial(MethodHandles.java:1231)
at ir.moke.MyInvocationHandler.invoke(MyInvocationHandler.java:12)
... 2 more
【问题讨论】:
-
你有什么问题?有错误吗?