• jdk动态代理 案例


    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    interface Person1 {
        public String eat();
        public String drink();
    }
    class Kid implements Person1{
        public String name;
        public Kid(String name) {
            this.name=name;
        }
        public String eat() {
            System.out.println("kids are eating!");
            return this.name;
        }
        public String drink() {
            System.out.println("kids are drinking!");
            return this.name;
        }
        
    }
    class MyInvocationHandler<T> implements InvocationHandler{
        //被代理对象
        private T target;
        public MyInvocationHandler(T target){
            this.target=target;
        }
        /**
         * 
         */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Object result;
            if("eat".equals(method.getName())) {
                System.out.println("洗手");
                result = method.invoke(target, args);
                System.out.println("刷碗");
            }else {
                result = method.invoke(target, args);
            }
            return result;    //反射方法的返回值
        }
        
    }
    public class ProxyDemos {
        public static void main(String[] args) throws NoSuchMethodException, SecurityException, Throwable {
            Person1 p=new Kid("小王");
            MyInvocationHandler<Person1> handle=new MyInvocationHandler<Person1>(p);
            Person1 kid=(Person1) Proxy.newProxyInstance(Person1.class.getClassLoader(), new Class<?>[]{Person1.class}, handle);
            System.out.println(kid.eat());
            System.out.println("--------------------");
            System.out.println(kid.drink());
        }
    }
    Output:

    洗手
    kids are eating!
    刷碗
    小王
    --------------------
    kids are drinking!
    小王

  • 相关阅读:
    hdu4930 模拟斗地主
    hdu4930 模拟斗地主
    hdu4923 f(A,B)分段处理
    hdu4923 f(A,B)分段处理
    poj2112 二分最大流+Floyd
    poj2112 二分最大流+Floyd
    POJ1149 PIGS(最大流)
    POJ1149 PIGS(最大流)
    对最大团的理解
    对最大团的理解
  • 原文地址:https://www.cnblogs.com/mryangbo/p/10756880.html
Copyright © 2020-2023  润新知