JDK动态代理简单使用(2)
JDK动态代理使用:
使用JDK动态代理步骤:
①创建被代理的接口和类;
public interface IA { void f1(String param); }
public class A implements IA { @Override public void f1(String param) { System.out.println("方法f1执行了........" + param); } }
②创建InvocationHandler接口的实现类,在invoke方法中实现代理逻辑;
public class MyInvocationHandler implements InvocationHandler { //被代理对象,Object类型 private Object target; public MyInvocationHandler(Object target){ this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("proxy start....."); Object invoke = method.invoke(target, args); System.out.println("proxy end......"); return invoke; } }
③通过Proxy的静态方法newProxyInstance( ClassLoaderloader, Class[] interfaces, InvocationHandler h)创建一个代理对象
④使用代理对象。
public class DynamicProxyTest { public static void main(String[] args) { IA target = new A(); InvocationHandler handler = new MyInvocationHandler(target); IA proxyInstance = (IA) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(), target.getClass().getInterfaces(), handler); proxyInstance.f1("XXX"); } }