如何使用动态代理?

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 方法的返回值是调用的真实对象的对应方法的返回值.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值