// ===== file:DynamicProxyFactory.java =====
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxyFactory {
/**
* 创建代理对象
* @param target : 必须实现某个接口的对象
* @return 代理对象
*/
public static Object newProxyInstance(final Object target) {
Object proxy = Proxy.newProxyInstance(target.getClass()
.getClassLoader(), target.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
System.out.println("before invoke");
Object returnValue = method.invoke(target, args);
System.out.println("after invoke");
return returnValue;
}
});
return proxy;
}
}
// ===== file:IProxy.java =====
public interface IProxy {
public String invoke();
}
// ===== file:ProxyObject.java =====
public class ProxyObject implements IProxy {
public String invoke() {
System.out.println("method invoke");
return "oldobject";
}
}
// ===== file:Test.java =====
public class Test {
public static void main(String[] args) {
ProxyObject oldobject = new ProxyObject();
IProxy newobject = (IProxy) DynamicProxyFactory.newProxyInstance(oldobject);
System.out.println(newobject.invoke());
}
}