I want to call default method of interface with InvocationHandler .
I have this code .
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));
}
}
I found only one example for default method reflection .
Update :
I receive this error :
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