一、Proxy代理方式:
1.适用方式: 适用于有接口的情况
2. 代码示例:
public class TestProxy { public static void main(String[] args) { Dog dog =new Dog(); Proxy.newProxyInstance(dog.getClass().getClassLoader(), dog.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { if ("eat".equals(method.getName())){ System.out.println("eat方法开始"); dog.eat(); System.out.println("eat方法结束"); }else if ("bark".equals(method.getName())){ System.out.println("sleep方法开始"); dog.sleep(); System.out.println("sleep方法结束"); }