2. 动态代理回顾: 动态代理是AOP的基础

接口和实现类:

public interface Interface {
    void doSomething();
    void somethingElse(String arg);
}
public class RealObject implements Interface {
    public void doSomething() {
        System.out.println("doSomething.");
    }
    public void somethingElse(String arg) {
        System.out.println("somethingElse " + arg);
    }
}

动态代理对象处理器:

public class DynamicProxyHandler implements InvocationHandler {
    private Object proxyed;
    
    public DynamicProxyHandler(Object proxyed) {
        this.proxyed = proxyed;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        System.out.println("代理工作了.");
        return method.invoke(proxyed, args);
    }
}

测试类:

public class Main {
    public static void main(String[] args) {
        RealObject real = new RealObject();
        Interface proxy = (Interface) Proxy.newProxyInstance(
                Interface.class.getClassLoader(), new Class[] {Interface.class},
                new DynamicProxyHandler(real));
        
        proxy.doSomething();
        proxy.somethingElse("zhw");
    }
}

结果:

代理工作了.
doSomething.
代理工作了.
somethingElse zhw

你可能感兴趣的:(2. 动态代理回顾: 动态代理是AOP的基础)