java - 具有默认接口方法的 Java 8 InvocationHandler
问题描述
我想用 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));
}
}
我只找到了一个默认方法反射的例子。
更新:
我收到此错误:
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
解决方案
在 的方法中,您可以执行以下CalculatorInvocation
操作来调用methodA
:Calculator
Calculater.super.methodA(int1, int2);
推荐阅读
- python - 如何使用 Tweepy 仅存储推文的文本
- c# - 如何在 C# 中从 MVC 控制器返回 Json 数据
- google-app-engine - 获取 ZONE_RESOURCE_POOL_EXHAUSTED
- email - imap.gmail.com 使用 Alpine 返回自签名证书
- python - 嵌套字典,元组列表作为python中DATA文件的值
- java - 调用具有相同前缀的不同变量仅更改后缀
- php - 我正在使用 select2 插件。点击SEND后如何使选中的选项不打?
- xml - 如何通过标签(Pretty Print)使用批处理脚本标签来格式化 XML?
- r - R使用函数summary_table和qwraps2时出错
- c# - 如何在 c# winforms 中显示小写字母的 KeyCode 和 KeyData