具有默认接口方法的Java 8 InvocationHandler

时间:2018-10-29 13:23:23

标签: java java-8

我想使用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

1 个答案:

答案 0 :(得分:0)

CalculatorInvocation方法中,您可以执行此操作以从methodA调用Calculator

Calculater.super.methodA(int1, int2);
相关问题