java动态代理学习

使用

直接上代码:

    public static void main( String[] args )
    {
    	IMDemo object = (IMDemo) Proxy.newProxyInstance(IMDemo.class.getClassLoader(),new Class[] {IMDemo.class}, new MHandler());
    	object.test("");
    }
    
    public class MHandler implements InvocationHandler{

		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			System.out.println("invoke_"+method.getName());
			return null;
		}
    }
    
    interface IMDemo{
    	int test(String p);
    }

java动态代理:动态构造一组接口的实现类,实现类中方法的调用都会以反射的形式在InvocationHandler接口的invoke方法中处理。

实现

查看源码:Proxy——>ProxyClassFactory——>ProxyGenerator

Proxy.newProxyInstance方法
public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
		......
        /*
         * 构造接口实现类
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * 使用反射实例化对象,使用带一个InvocationHandler 参数的构造函数
         */
        try {
        	......
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
 		......
    }

2、然后在getProxyClass0函数中看到从WeakCache对象中取缓存的实现类。
3、如果没有则用ProxyClassFactory构造实现类并保存到缓存对象中。
4、在ProxyClassFactory的apply函数中,调用ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags)方法构造实现类的二进制字节码,然后使用一个native函数defineClass0构造实现了的Class对象。
5、ProxyGenerator.generateClassFile 手动构造字节码。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值