动态代理定义:A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.
可参看 http://java.sun.com/j2se/1.4.2/docs/guide/reflection/proxy.html
这是一个简单的例子:
接口:
public interface Foo {
Object bar(Object obj) throws Exception;
}
一个简单实现:
public class FooImple implements Foo {
public Object bar(Object obj) throws Exception {
System.out.println("method executing ...");
return obj;
}
}
代理类:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DebugProxy implements java.lang.reflect.InvocationHandler {
private Object obj;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new DebugProxy(obj));
}
private DebugProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
try {
//System.out.println("proxy is " + proxy.getClass().getName());
System.out.println("before method " + m.getName());
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: "
+ e.getMessage());
} finally {
System.out.println("after method " + m.getName());
}
return result;
}
}
测试类:
public class test {
public static void main(String[] args) throws Exception {
Foo foo = (Foo) DebugProxy.newInstance(new FooImple());
foo.bar(new String("test"));
}
}
测试结果:
D:y>java -classpath . test
before method bar
method executing ...
after method bar