靜態代理
我們定義一個介面,並且使用代理模式,想要做到的就是在呼叫這個介面的實現類時在此方法上新增功能。
public interface HelloInterface {
void sayHello();
}
接下來就是這個介面的實現類,我們在呼叫sayHello時輸出一句話:
public class Hello implements HelloInterface{
@Override
public void sayHello() {
System.out.println("hello world");
}
}
然後我們設計代理類:
/**
* 靜態代理
*/
public class StaticHelloProxy implements HelloInterface{
private HelloInterface helloInterface = new Hello();
@Override
public void sayHello() {
System.out.println("say hello before invoke");
helloInterface.sayHello();
System.out.println("say hello after invoke");
}
}
這樣我們就實現了靜態代理,StaticHelloProxy這個類去代理Hello類。並且給方法擴充套件了功能。
動態代理
我們在剛剛的靜態代理中發現了一個問題,StaticHelloProxy這個代理只能代理Hello這個類,如果有其他的類需要代理,我們就需要更多的代理類,這不是我們想要的。那麼能不能在同一個類中代理更多的類呢?實際上通過反射是可以做到的。
public class ProxyHandle implements InvocationHandler {
private Object object;
public ProxyHandle(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("say hello before invoke" + method.getName());
method.invoke(object, args);
System.out.println("say hello after invoke" + method.getName());
return null;
}
}
我們定義了一個ProxyHandle,在構造方法中將需要的物件傳入,並且通過反射呼叫方法。當然呼叫也不太一樣。
public static void main(String[] args) {
HelloInterface helloInterface = new Hello();
InvocationHandler handler = new ProxyHandle(helloInterface);
HelloInterface proxyHello = (HelloInterface) Proxy.newProxyInstance(helloInterface.getClass().getClassLoader(),helloInterface.getClass().getInterfaces(),handler);
proxyHello.sayHello();
}
這樣子就實現了動態代理。