本帖最后由 朱玉玺 于 2013-1-30 00:50 编辑
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.List;
- interface Advice {
- void beforeMethod(Method method);
- void afterMethod(Method method);
- }
- class MyAdvice implements Advice {
- long startTime=0;
- @Override
- public void beforeMethod(Method method) {
- System.out.println("方法开始啦");
- startTime = System.currentTimeMillis();
- }
- @Override
- public void afterMethod(Method method) {
- System.out.println("方法结束啦");
- long endTime = System.currentTimeMillis();
- System.out.println(method.getName()+" running time:"+(endTime - startTime));
- }
- }
- public class ProxyTest {
- public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- final ArrayList target = new ArrayList();
- Collection proxy =(Collection) getProxy(target,new MyAdvice());
- // ArrayList it =(ArrayList) getProxy(target,new MyAdvice()); 这句报错
- List proxy1 =(List) getProxy(new ArrayList(),new MyAdvice());
- Iterable it = (Iterable)getProxy(new ArrayList(),new MyAdvice());
- /*
- 我的问题:1.这里的getProxy()方法传递的参数是final类型的,但为什么我传入new ArrayList()没有定义成final,没有定义成final也通过编译而且运行正常?
- 2.这里的代理设计模式,跟装饰设计模式很类似,都是传入一个类,然后返回一个新类,同时多了一些功能,这两个设计模式有什么区别?
- 3.Collection 能指向这个代理类,说明这个代理类是Collection的一个实现类,但也没有标记implement怎么就实现了?
- 将其强转为ArrayList编译失败,说明它是不是ArrayList或者其子类,它跟ArrayList的最大公约数是什么?
- */
- // System.out.println("iterable:"+it.iterator());
- proxy1.add("lisi");
- proxy.add("wangwu");
- System.out.println(proxy.size());
-
- }
- public static Object getProxy(final Object target,final Advice advice) {
- Object proxy3 =Proxy.newProxyInstance(
- target.getClass().getClassLoader(),
- target.getClass().getInterfaces(),
- new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- advice.beforeMethod(method);
- Object retVal = method.invoke(target, args);
- advice.afterMethod(method);
- return retVal;
- }
- });
- return proxy3;
- }
- }
复制代码 |