Proxy.newProxyInstance()创建proxy
GitHub Code: feat: java.lang.reflect里的方法Proxy.newProxyInstance()创建proxy
java.lang.reflect自带的方法Proxy.newProxyInstance()创建proxy
public class ArithmeticCalculatorLogProxy {
private ArithmeticCalculatorService target;
public ArithmeticCalculatorLogProxy(ArithmeticCalculatorService target) {
this.target = target;
}
public ArithmeticCalculatorService getProxy() {
ClassLoader classLoader = target.getClass().getClassLoader();
Class[] interfaces = new Class[]{ArithmeticCalculatorService.class};
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method:" + method.getName() + ", args=" + Arrays.toString(args));
Object result = method.invoke(target, args);
System.out.println("method:" + method.getName() + ", result=" + result);
// System.out.println(proxy); // 打印这个会StackOverflowError
return result;
}
};
ArithmeticCalculatorService proxy = (ArithmeticCalculatorService)Proxy.newProxyInstance(classLoader, interfaces, handler);
return proxy;
}
}Last updated
Was this helpful?