java动态代理

Proxy类

动态代理类实现在运行时指定得接口列表。每个代理实例会有一个相关联得invocation handler实例(实现了InvocationHandler接口)。代理对象得方法调用会分发到invocation handler实例得invoke方法。Invocation handler实例处理方法调用,返回得结果作为代理实例方法调用得结果。

static Object 	newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
/*
Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.
*/

InvocationHandler类

每个代理类得接口方法调用都分发给InvocationHandler对象得invoke方法。

Object invoke(Object proxy,
              Method method,
              Object[] args)
       throws Throwable
/*
Processes a method invocation on a proxy instance and returns the result. 
This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with.
*/

例子

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
        RealSubject beingProxiedObject = new RealSubject();
        ProxyClass proxyObject = new ProxyClass(beingProxiedObject);
        Subject subject = (Subject)
                Proxy.newProxyInstance(beingProxiedObject.getClass().getClassLoader(), beingProxiedObject.getClass().getInterfaces() ,proxyObject);

        subject.f();
    }


}

interface Subject{
    void f();
}

class ProxyClass implements InvocationHandler {

    RealSubject beingProxiedObject;

    public ProxyClass(RealSubject beingProxiedObject) {
        this.beingProxiedObject = beingProxiedObject;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before beingProxiedObject method invocation");

        Object object = method.invoke(beingProxiedObject, args);

        System.out.println("after beingProxiedObject method invocation");
        return object;
    }
}



class RealSubject implements Subject{
    public void f() {
        System.out.println("being proxied");
    }
}

分析
Proxy.newInstance是根据接口创建一个实例(不是RealSubject类对象,或者InvocationHandler对象),通过 Proxy.newProxyInstance 创建的代理对象是在jvm运行时动态生成的一个对象,是在运行是动态生成的一个对象,并且命名方式都是这样的形式,以$开头,proxy为中,最后一个数字表示对象的标号。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值