Java动态代理Proxy
Java动态代理Proxy
规则:
-
必须实现接口编程;需要一个接口,目标类实现该接口。
-
必须实现InvocationHandler接口;为目标对象实现增强功能。
例子:
public interface IHelloWorld { void print(); } public class HelloWorldImpl implements IHelloWorld { @Override public void print() { System.out.println("hello world"); } } public class InvocationHandlerDemo implements InvocationHandler { private Object target; public InvocationHandlerDemo(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("invocationHandler before"); Object obj = method.invoke(target, args); System.out.println("invocationHandler after"); return obj; } } public class ProxyApplication { public static void main(String[] args) throws Exception { // 模式1 IHelloWorld pd = (IHelloWorld) Proxy.newProxyInstance(IHelloWorld.class.getClassLoader(), new Class[] {IHelloWorld.class}, new InvocationHandlerDemo(new HelloWorldImpl())); pd.print(); System.out.println("-------------------"); // 模式2 Class<?> proxyClass = Proxy.getProxyClass(IHelloWorld.class.getClassLoader(), IHelloWorld.class); InvocationHandler ih = new InvocationHandlerDemo(new HelloWorldImpl()); IHelloWorld pd2 = (IHelloWorld) proxyClass.getConstructor(InvocationHandler.class).newInstance(ih); pd2.print(); } } // 结果 invocationHandler before hello world invocationHandler after ------------------- invocationHandler before hello world invocationHandler after
原理: