import java.lang.reflect.*;
import java.util.Arrays;
public class Test4{
public static void main(String[] args) {
yunsuanin yuansuan1 = (yunsuanin) Proxy.newProxyInstance(
yunsuanin.class.getClassLoader(), //此处必须为Interface,否则报错
new Class[] {yunsuanin.class}, //此处必须为Interface,否则报错
new Dynamic(new yunsuan()));
yuansuan1.add(1, 2);
}
}
class Dynamic implements InvocationHandler {
Object obj;
public Dynamic(Object obj) {
super();
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method is :" + method.getName() + ", begin with" + Arrays.asList(args).toString() + method.);
Object result = method.invoke(obj, args);
System.out.println("end with:" + result);
return result;
}
}
class yunsuan implements yunsuanin{
public int div(int i, int j) {
return i / j;
}
public int add(int i, int j) {
return i + j;
}
}
interface yunsuanin {
public int div(int i, int j);
public int add(int i, int j);
}
运行结果截图:
关于 Proxy 类
Proxy 主要是提供了 Proxy.newProxyInstance 静态方法, 其签名如下:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
此静态方法需要三个参数:
loader: 即类加载器, 指定由哪个ClassLoader对象来对生成的代理对象进行加载
interfaces: 一个Interface对象的数组, 表示的是代理对象所需要实现的接口.
h: 即 InvocationHandler 的实现对象. 当调用代理对象的接口时, 实际上会 通过 InvocationHandler.invkoe 将调用转发给实际的对象.
这个静态类会返回一个代理对象, 在程序中可以可通过这个代理对象来对实际对象进行操作.
关于 InvocationHandler 接口
我们在前面提到过, 在调用 Proxy.newProxyInstance 方法时, 需要传递一个 InvocationHandler 接口的实现对象, 那么这个 InvocationHandler 接口有什么用呢?
实际上, 在 Java 动态代理中, 我们都必须要实现这个接口, 它是沟通了代理对象和实际对象的桥梁, 即:
InvocationHandler is the interface implemented by the invocation handler of a proxy instance.
Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.
当我们调用了代理对象所提供的接口方法时, 此方法调用会被封装并且转发到 InvocationHandler.invoke 方法中, 在 invoke 方法中调用实际的对象的对应方法.
InvocationHandler.invoke 方法的声明如下:
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
这个方法接收三个参数:
proxy: 指代理对象, 即 Proxy.newProxyInstance 所返回的对象(注意, proxy 并不是实际的被代理对象)
method: 我们所要调用真实对象的方法的 Method 对象
args: 调用真实对象某个方法时接受的参数
invoke 方法的返回值是调用的真实对象的对应方法的返回值.