【问题标题】:Java 8 InvocationHandler with default interface method [duplicate]具有默认接口方法的 Java 8 InvocationHandler [重复]
【发布时间】: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

【问题讨论】:

  • 你有什么问题?有错误吗?

标签: java java-8


【解决方案1】:

CalculatorInvocation 的方法中,您可以这样做从Calculator 调用methodA

Calculater.super.methodA(int1, int2);

【讨论】:

  • 如何使用方法处理程序?
猜你喜欢
  • 2018-01-28
  • 2015-03-17
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多