动态代理

public interface Subject {
    public void doSome();
}
public class Aminor implements Subject {
    public void doSome() {
        System.out.println("被代理对象执行");
    }
}
public class AminorProxy implements InvocationHandler {
    private Object tar;

    public Object bind(Object tar) {
        this.tar = tar;
        return Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // TODO Auto-generated method stub
        Object result = null;
        System.out.println("被代理对象执行前执行的事");
        result = method.invoke(tar, args);
        System.out.println("被代理对象执行后执行的事");
        return result;
    }

}
public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AminorProxy proxy = new AminorProxy();
        Subject sub = (Subject) proxy.bind(new Aminor());
        sub.doSome();
    }
}

你可能感兴趣的:(动态代理)