動態(tài)代理主要用來做方法的增強,可以讓你在不修改源碼的情況下,可以在方法執(zhí)行前插入一些公共方法,或者在方法執(zhí)行后插入一些公共方法(AOP)。如果方法比較多,且方法具有相似性的情況下,可以只定義接口,通過動態(tài)代理來實現(xiàn)接口,極大的減少代碼量。實現(xiàn)無侵入式的代碼擴展。
首先定義一個接口:
public interface TestInterface {
void test(String str);
}
實現(xiàn)該接口:
public class TestImplement implements TestInterface {
@Override
public void test(String str) {
System.out.println(str);
}
}
動態(tài)代理類:
public class TestProxy implements InvocationHandler{
private Object obj;
public TestProxy(Object obj){
this.obj = obj;
}
public TestProxy(){}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
//do something before
result = method.invoke(obj, args);//調用實例方法。
//do something after
return result;
}
}
動態(tài)代理測試:
public static void main(String[] args) {
TestInterface i = new TestImplement();//獲取被代理類
TestProxy proxy = new TestProxy(i);//動態(tài)代理類
Class<?> clazz = i.getClass();
TestInterface t = (TestInterface)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), proxy);
t.test("xx");
}
上面的t
是生成出來的動態(tài)代理實例,是Proxy的一個實例$Proxy0
該實例實現(xiàn)了TestInterface
接口。故當調用test()
方法的時候就會走到TestProxy.invoke
方法。可以在TestProxy
中自定義業(yè)務邏輯。實現(xiàn)無侵入式代碼擴展。當然也可以不需要TestImplement
實現(xiàn)類,只需要在invoke
方法中根據(jù)參數(shù)來自定義實現(xiàn)。所以就會有一些框架代碼看起來比較神奇,比如Retrofit
、Mybatis
等只需要定義接口。不需要對接口進行實現(xiàn)。
Retrofit
概念
一個類型安全的HTTP客戶端,是注解形式的封裝庫。是一個基于OkHttp的包裝庫,使用簡單,只需要定義接口加上注解即可。
使用方法
引用retrofit、gson依賴,gson用來將json數(shù)據(jù)轉換為object
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
然后自定義接口用來獲取想要的數(shù)據(jù)。在接口上以注解或者參數(shù)的方式將遠程API接口所需要的參數(shù)配置上去。
再用Retrofit.create出接口的實例即可使用。源碼如下:
public <T> T create(final Class<T> service) {
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, Object... args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
這里使用了動態(tài)代理機制。可以看出在實現(xiàn)InvocationHandler里面,解析了method中的注解,和參數(shù)。拼成OkHttp參數(shù)請求發(fā)送再返回。
Mybatis
跟retrofit很相似,mybatis也是利用動態(tài)代理,用戶只需要定義接口即可。利用參數(shù)和注解生成sql。不同的時mybatis的接口方法命名決定了sql執(zhí)行命令CRUD。
MapperProxy的invoke方法如下:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
在MapperProxyFactory中獲取代理類。
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
跟retrofit基本一樣,兩者都使用了cached,將接口的實例緩存起來。
一句話總結
動態(tài)代理是為其他對象提供一種代理以控制這個對象的方法。