浅析Java代理机制

简单代理

重点在于代理类和被代理类实现 同一个 接口。

// 接口
public interface MyInterface {
    void doSomething();
    void somethingElse(String arg);
}
// 被代理类
public class RealObject implements MyInterface {
    public void doSomething() {
        System.out.println("RealObject.doSomething().");
    }
    public void somethingElse(String arg) {
        System.out.println("RealObject.somethingElse(" + arg + ").");
    }
}
// 代理类
public class MyInterfaceProxy implements MyInterface {
    private MyInterface proxy;
    private int cnt = 0;
    public MyInterfaceProxy(MyInterface proxy) {
        this.proxy = proxy;
    }
    public void doSomething() {
        System.out.println("Proxy.doSomething() called: " + ++cnt);
        proxy.doSomething();
    }
    public void somethingElse(String arg) {
        System.out.println("Proxy.somethingElse(" + arg + ").");
        proxy.somethingElse(arg);
    }
}
// 测试
public class TestProxy {
    public static void testProxy(MyInterface mi) {
        mi.doSomething();
        mi.doSomething();
        mi.somethingElse("bang-bang-bang");
    }
    public static void main(String[] args) {
        MyInterface mi1 = new MyInterfaceProxy(new RealObject());
        testProxy(mi1);
    }
}

动态代理

从上面可以看到,丫的,代理类必须实现跟被代理类一样的接口,这种简直属于没天理的行为。所以Java提供了InvocationHandler来实现动态代理。运用到的原理包括:

  1. Object作为所有类的基类,被代理类会被转化为此类型。
  2. 反射机制。

你可能感兴趣的:(浅析Java代理机制)