1、寫一個(gè) ArrayList 的動(dòng)態(tài)代理類(筆試題)
final List<String> list = new ArrayList<String>();
List<String> proxyInstance =
(List<String>) Proxy.newProxyInstance(list.getClass().getClassLoader(),
list.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(list, args);
}
});
proxyInstance.add("你好");
System.out.println(list);
2、動(dòng)靜態(tài)代理的區(qū)別,什么場(chǎng)景使用?
● 靜態(tài)代理通常只代理一個(gè)類,動(dòng)態(tài)代理是代理一個(gè)接口下的多個(gè)實(shí)現(xiàn)類。
● 靜態(tài)代理事先知道要代理的是什么,而動(dòng)態(tài)代理不知道要代理什么東西,只有在運(yùn)行時(shí)才知道。
動(dòng)態(tài)代理是實(shí)現(xiàn)JDK里的InvocationHandler接口的invoke方法,但注意的是代理的是接口,也就是你的業(yè)務(wù)類必須要實(shí)現(xiàn)接口,通過Proxy里的newProxyInstance得到代理對(duì)象。還有一種動(dòng)態(tài)代理CGLIB,代理的是類,不需要業(yè)務(wù)類繼承接口,通過派生的子類來實(shí)現(xiàn)代理。通過在運(yùn)行時(shí),動(dòng)態(tài)修改字節(jié)碼達(dá)到修改類的目的。AOP編程就是基于動(dòng)態(tài)代理實(shí)現(xiàn)的,比如著名的Spring框架、Hibernate框架等等都是動(dòng)態(tài)代理的使用例子。