Loading

代理模式之动态代理

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();
    }
}

测试结果:

 

 

 
posted @ 2020-08-06 11:16  揸火箭  阅读(127)  评论(0编辑  收藏  举报

Loading