1.什麼是代理(中介)?
通俗的說就是通過第三方進行兩個人交易,比如租房,代理對象是黑中介——有租房子的方法(此時的方法爲調用房東租房的方法),被代理對象/目標對象是房東——真正的租房的方法,執行代理對象方法的對象是租房者。
代理的流程可以看成:
租房者租房——中介(租房的方法)——房東(租房的方法)
抽象爲:調用對象——代理對象——目標對象
2.動態代理
不用手動編寫一個代理對象,不需要編寫與目標對象相同的方法,這個過程,在運行時的內存中動態生成代理對象。------字節碼對象級別的代理對象
在java中有動態代理的API:
在jdk的API中存在一個Proxy中存在一個生成動態代理的的方法newProxyInstance:
static Object | newProxyInstance( ClassLoader loader, Class<?>[]interfaces, InvocationHandler h) |
返回值:Object就是代理對象
參數:loader:代表與目標對象相同的類加載器-------目標對象.getClass().getClassLoader()
interfaces:代表與目標對象實現的所有的接口字節碼對象數組
h:具體的代理的操作,InvocationHandler接口
代碼如下:
目標對象代碼:
package Proxy;
public class Target implements TargetInterface {
@Override
public void method() {
System.out.println("fangfayi");
}
@Override
public String method1() {
System.out.println("method1。。。。");
return "method1";
}
}
自己創建的接口代碼:package Proxy;
public interface TargetInterface {
public void method();
public String method1();
}
代理對象代碼:
package Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
final Target target=new Target();
TargetInterface proxy=(TargetInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
//代理對象調用接口相應方法都是調用invoke
//proxy:是代理對象
//method:代表的是目標方法的字節碼對象
//args:代表的是調用目標方法時參數
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//反射
Object invoke=method.invoke(target, args);//目標對象的相應方法
return null;
}
}
);
proxy.method();//調用invoke方法-----Method:目標對象的method方法 args:null
proxy.method1();//調用invoke方法-----Method1:目標對象的method1方法 args:null
}
}
注意:JDK的Proxy方式實現的動態代理 目標對象必須有接口 沒有接口不能實現jdk版動態代理。