import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Calculator {
int add(int a, int b);
}
class CalculatorHandler implements InvocationHandler {
private final Calculator target;
public CalculatorHandler(Calculator target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method call");
Object result = method.invoke(target, args);
System.out.println("After method call");
return result;
}
}
public class DynamicProxyExample {
public static void main(String[] args) {
Calculator realCalculator = (a, b) -> a + b;
Calculator proxyCalculator = (Calculator) Proxy.newProxyInstance(
Calculator.class.getClassLoader(),
new Class[] { Calculator.class },
new CalculatorHandler(realCalculator)
);
int result = proxyCalculator.add(2, 3);
System.out.println("Result: " + result);
}
}
标签:target,int,Calculator,Object,代理,result,动态,method,举例说明
From: https://www.cnblogs.com/jintaocode/p/17631342.html