1、寫一個 ArrayList 的動態代理類(筆試題)
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、動靜態代理的區別,什么場景使用?
● 靜態代理通常只代理一個類,動態代理是代理一個接口下的多個實現類。
● 靜態代理事先知道要代理的是什么,而動態代理不知道要代理什么東西,只有在運行時才知道。
動態代理是實現JDK里的InvocationHandler接口的invoke方法,但注意的是代理的是接口,也就是你的業務類必須要實現接口,通過Proxy里的newProxyInstance得到代理對象。還有一種動態代理CGLIB,代理的是類,不需要業務類繼承接口,通過派生的子類來實現代理。通過在運行時,動態修改字節碼達到修改類的目的。AOP編程就是基于動態代理實現的,比如著名的Spring框架、Hibernate框架等等都是動態代理的使用例子。