IHello.java
package org.springsource.proxy;
/**
* @author billzhang
*
*/
public interface IHello {
void sayHello(String name);
}
HelloImpl.java
package org.springsource.proxy;
/**
* @author billzhang
*
*/
public class HelloImpl implements IHello {
public void sayHello(String name) {
System.out.println("Hello "+name);
}
}
Static Proxy:
StaticProxy.java
package org.springsource.proxy.stac;
import org.springsource.proxy.IHello;
/**
* @author billzhang
*
*/
public class StaticProxy implements IHello{
private IHello hello;
public StaticProxy(IHello hello) {
super();
this.hello = hello;
}
public void sayHello(String name){
System.out.println("Start........");
hello.sayHello(name);
System.out.println("End..........");
}
}
从上面我们看到代理对象的一个接口只服务于一种类型的对象,如果您要代理的方法很多,势必要为每个方法进行代理,static proxy 在程式规模稍大时就必定无法胜任。
Java在JDK 1.3之后加入协助开发Dynamic Proxy功能的类别,我们不必为特定对象与方法编写特定的代理,使用Dynamic Proxy,可以使得一个handler服务于各个对象,首先,一个handler必须实现 java.lang.reflect.InvocationHandler:
DynamicProxy.java
package org.springsource.proxy.dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author billzhang
*
*/
public class DynamicProxy implements InvocationHandler{
private Object delegate;
public Object bind(Object delegate) {
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
System.out.println("Start "+method.getName()+"()");
result = method.invoke(delegate, args);
System.out.println("End "+method.getName()+"()");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
package org.springsource.proxy.main;
import org.springsource.proxy.HelloImpl;
import org.springsource.proxy.IHello;
import org.springsource.proxy.dynamic.DynamicProxy;
/**
* @author billzhang
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
//static proxy
/*IHello hello = new StaticProxy(new HelloImpl());
hello.sayHello("Bill");*/
//dynamic proxy
DynamicProxy dp = new DynamicProxy();
IHello hello = (IHello) dp.bind(new HelloImpl());
hello.sayHello("Bill");
}
}