所谓Dynamic Proxy是这样一种class: 它是在运行时生成的class,在生成它时你必须提供一组interface给它,然后该class就宣称它实现了这些interface。你当然可以把该class的实例当作这些interface中的任何一个来用。当然啦,这个Dynamic Proxy其实就是一个Proxy,它不会替你作实质性的工作,在生成它的实例时你必须提供一个handler,由它接管实际的工作。用一个例子来解释(例子包含三个java文件,已经调试通过):
//ProxyClass.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
public class ProxyClass
{
public static void main(String arags[]) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException
{
InvocationHandler handler = new MyInvocationHandler();
Class proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(),
new Class[] { Foo.class });
Foo f = (Foo) proxyClass.getConstructor(
new Class[] { InvocationHandler.class }).newInstance(
new Object[] { handler });
f.doSomething();
}
}
//Foo.java
public interface Foo
{
void doSomething();}
//MyInvocationHandler.javaimport java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class MyInvocationHandler implements InvocationHandler
{
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
System.out.println("Helloworld");
return null;
}
} |