JAVA基础

1、Java中的静态代理与动态代理

1)、静态代理

创建一个接口,然后创建被代理的类实现该接口并且实现该接口中的抽象方法。之后再创建一个代理类,同时使其也实现这个接口。在代理类中持有一个被代理对象的引用,而后在代理类方法中调用该对象的方法。

public class ProxyCoreTest {

    public static void main(String[] args) {
        StudentInterface studentInterface = new StudentProxy();
        studentInterface.sayHello();
    }
}

interface StudentInterface{
    void sayHello();
}

class Xiaowang implements StudentInterface{

    @Override
    public void sayHello() {
        System.out.println("我是小王 你好.");
    }
}

class StudentProxy implements StudentInterface{

    StudentInterface studentInterface;
    public StudentProxy(){
        studentInterface = new Xiaowang();
    }

    @Override
    public void sayHello() {
        System.out.println("前置增强");

        studentInterface.sayHello();

        System.out.println("后置增强");
    }
}

2、动态代理

主要是通过实现InvocationHandler内的invoke方法实现。

public class ProxyCoreTest {
    public static void main(String[] args) {
        XiaoWang xiaoWang = new XiaoWang();
        ProxyFilter proxyFilter = new ProxyFilter(xiaoWang);
        Object o = Proxy.newProxyInstance(xiaoWang.getClass().getClassLoader(), xiaoWang.getClass().getInterfaces(), proxyFilter);
        System.out.println(o);

    }
}

/**
 * invoke方法内部实现增强
 */
class ProxyFilter implements InvocationHandler{
    Object obj;
    public ProxyFilter(Object obj){
        this.obj = obj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("前置增强");
        Object invoke = method.invoke(obj, args);
        System.out.println("后置增强");
        return invoke;
    }
}

interface Student{
    String sayHi();
}

class XiaoWang implements Student{

    @Override
    public String sayHi() {
        System.out.println("你好我是小王");
        return "小王";
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容