jdk动态代理(暂)

 

 

代理模式:

假设有一个类A(实现了InterfaceOne接口),现在再定义一个类AProxy。

如果需要访问A的某个方法,则通过访问AProxy中特定方法,由AProxy中的方法(不一定和A的方法对应)来调用A中的相应方法,即AProxy 是A的代理。

 

jdk的动态代理(Proxy):

即jdk提供了Proxy这个类,实现代理模式。即把 AProxy 和 A绑定起来,当要访问A的时候,自动先访问AProxy。

 

使用方法:

A a = new A();

AProxy a_proxy = new AProxy();

InterfaceOne itf1 =(InterfaceOne ) Proxy.newProxyInstance(a.getClassLoader, a_proxy.getInterfaces,a_proxy),

 

itf1.func(); // 调用相应的方法之后,就会进入动态代理的invoke之中.

 

我个人对动态代理中动态的理解是:动态即在java.reflect.Proxy可以绑定  代理类(实现InvocationHandler接口) 和 被代理类.

这种绑定是不需要在编码的时候就写死,而是在运行时进行绑定.!

 

 

代码````````````

package dynamicProxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Test { static public void main(String[] args) { A a = new A(); AProxy a_proxy = new AProxy(a); // Returns an instance of a proxy class for the specified interfaces // that dispatches method invocations to the specified invocation // handler. This method is equivalent to: InterfaceOne itf1 = (InterfaceOne) Proxy.newProxyInstance(a.getClass() .getClassLoader(), a.getClass().getInterfaces(), a_proxy); itf1.add(); } } interface InterfaceOne { void add(); } class A implements InterfaceOne { public void add() { System.out.println("A:Add()"); } } class AProxy implements InvocationHandler { A a = new A(); AProxy(A a) { this.a = a; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("In the proxy! Before calling /n/t" + method); method.invoke(a, args); System.out.println("after calling /n/t" + method); return null; }

你可能感兴趣的:(jdk动态代理(暂))