zoukankan      html  css  js  c++  java
  • 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!
    小王

  • 相关阅读:
    [JLOI2010] 冠军调查
    [ZJOI2009] 狼和羊的故事
    [CF1451D] Circle Game
    [CF1451E1] Bitwise Queries (Easy Version)
    [CF343D] Water Tree
    [CF1344B] Monopole Magnets
    [CF191C] Fools and Roads
    [CF1370D] Odd-Even Subsequence
    [CF1366D] Two Divisors
    [CF1359D] Yet Another Yet Another Task
  • 原文地址:https://www.cnblogs.com/mryangbo/p/10756880.html
Copyright © 2011-2022 走看看