zoukankan      html  css  js  c++  java
  • 代理模式之动态代理

    1.使用JDK反射

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    /**
     * @作者 five-five
     * @创建时间 2020/8/6
     */
    public class Demo01 implements InvocationHandler {
        public Object target;
    
        public Object newInstance() {
            return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return method.invoke(target, args);
        }
    }

    测试代码:

    /**
     * @作者 five-five
     * @创建时间 2020/8/6
     */
    public interface Student {
        void study();
        void eat();
        void sleep();
    }
    
    
    /**
     * @作者 five-five
     * @创建时间 2020/8/6
     */
    public class StudentImpl implements Student{
        @Override
        public void study() {
            System.out.println("学生学习");
        }
    
        @Override
        public void eat() {
            System.out.println("学生吃饭");
    
        }
    
        @Override
        public void sleep() {
            System.out.println("学生睡觉");
    
        }
    }
    
    
    
    public class Client {
        public static void main(String[] args) {
            Demo01 demo01 = new Demo01();
            demo01.target=new StudentImpl();
            Object o = demo01.newInstance();
            Student stu=(Student)o;
            stu.eat();
            stu.sleep();
            stu.study();
        }
    }

    测试结果:

     
  • 相关阅读:
    周总结(第十一周)
    周总结(第十周)
    周总结(第九周)
    周总结(第八周)
    周总结(第七周)
    周总结(第六周)
    周总结(第5周)
    周总结(第四周)
    周记
    补周记
  • 原文地址:https://www.cnblogs.com/five-five/p/13445088.html
Copyright © 2011-2022 走看看