动态之反射

动态代理

所谓动态代理, 即通过代理类: Proxy 的代理  ,  接口和实现类之间可以不直接发生联系,而可以在在运行期间

(Runtime)实现动态关联。


  Java动态代理主要是使用

import java.lang.reflect.Proxy包中的两个类。


InvocationHandler
public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable;

参数说明: proxy :要代理的对象,method被代理的方法,被代理方法的参数

 
     
 Proxy
* @param loader     the class loader to define the proxy class
* @param interfaces the list of interfaces for the proxy class
*                   to implement
* @param h          the invocation handler to dispatch method invocations to
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h)
        throws IllegalArgumentException {
    Objects.requireNonNull(h);

    final Class<?>[] intfs = interfaces.clone();


 具体实例   中介与房东之间的代理与被代理关系:


1.申明一个抽象接口


public interface IRenting {

    /**
     * 租房子
     */
    public void rent();
}


2.目标对象(实现的接口类)


/**
 * @author :created by ${yangpf}
 * 房东
 */
public class Landlord implements IRenting {

    @Override
    public void rent() {
        System.out.print("--------------房东要出租房子" + "\n");
    }
}
 
 

3.代理对象

**
 * @author :created by ${yangpf}
 * 中介  代理类
 */
public class ProxynItermediary implements InvocationHandler {
    private IRenting iRenting;

    public ProxynItermediary(IRenting iRenting) {
        this.iRenting = iRenting;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.print("--------------中介带房客看房子....." + "\n");
//以反射(reflection)的形式引用真实对象的方法
        method.invoke(iRenting, args);

        System.out.print("--------------中介收取中介费......." + "\n");
        return null;
    }
}

测试:


public class Test {
    @org.junit.Test
    public void testMethod(){

        IRenting iRenting = new Landlord();

        ProxynItermediary proxy = new ProxynItermediary(iRenting);
        //动态创建代理对象
        IRenting object = (IRenting) Proxy.newProxyInstance(iRenting.getClass().getClassLoader(), iRenting.getClass().getInterfaces(), proxy);
        object.rent();

    }
}


输出结果:


--------------中介带房客看房子.....
--------------房东要出租房子
--------------中介收取中介费.......



猜你喜欢

转载自blog.csdn.net/u014133119/article/details/80512282