动态代理类

package com.fanShe;



import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

/**

 * 动态代理类: 

 * 我的理解是: 可以把多个接口中的 方法 统一用 类 的形式管理和使用

 * @param args

 */

interface Persons{

    void walk();

    void sayHello(String name);

}



//相当一个中介 动态代理类 中 接口的方法, 都要靠这个接口中的invoke来实现

class MyInvokationHandler implements InvocationHandler{



    /*

     * 三个参数的理解

     * prox:代表 动态代理对象

     * method: 代表 正在执行的方法

     * args: 代表 调用method方法时传入的实参

     */

    public Object invoke(Object proxy,Method method, Object[] args){

        System.out.println("--正在执行的方法: "+method);

        if(args !=null){

            System.out.println("下面是执行该方法时传来的实参为: ");

            for(Object val : args){

                System.out.println(val);

            }

        }else {

            System.out.println("调用该方法没有实参!");

        }

        return null;

    }

}

public class ProxyTest {



    

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        InvocationHandler handler = new MyInvokationHandler();

        /*Proxy :提供创建动态代理类的静态方法

         * 

         * Proxy.newProxyInstance(loader, interfaces, h)

         * 该方法 创建接口的一个实例

         * loader: 类加载器

         * interface: 接口的class 对象

         * h: InvocationHandler 的一个实例

         */

        Persons p =(Persons)Proxy.newProxyInstance(Persons.class.getClassLoader(), new Class[]{Persons.class}, handler);

        p.walk();

        

        p.sayHello("shaoshao");

    }

}

 

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