A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 虎牛龙马 中级黑马   /  2014-3-21 11:57  /  1516 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package cn.itcast.day8;
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;
public class ProxyTest {
/**
  * @param args
  * @throws NoSuchMethodException
  * @throws SecurityException
  * @throws InvocationTargetException
  * @throws IllegalAccessException
  * @throws InstantiationException
  * @throws IllegalArgumentException
  */
public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
  
  Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
  
  Collection proxy3 = (Collection) Proxy.newProxyInstance(
    Collection.class.getClassLoader(),
    new Class[] {Collection.class},
    new InvocationHandler(){
     ArrayList target = new ArrayList();
     @Override
     public Object invoke(Object proxy, Method method, Object[] args)
       throws Throwable {
      long startTime = System.currentTimeMillis();
      Object returnVal = method.invoke(target, args);
      long endTime = System.currentTimeMillis();
      System.out.println(method.getName() + ":runing time of:" + (endTime - startTime));
      return returnVal;
     }
     
    }
    );
  proxy3.add("baba");
  proxy3.add("mama");
  proxy3.add("hehe");
  System.out.println(proxy3);
  System.out.println(proxy3.size());
  System.out.println(proxy3.getClass());

}
}

结果:
add:runing time of:0
add:runing time of:0
add:runing time of:0
toString:runing time of:0
[baba, mama, hehe]
size:runing time of:0
3
class $Proxy0




提问:
jdk1.6中说道:
如果代理接口包含某一方法,它的名称和参数签名与 java.lang.Object 的 hashCode、equals 或 toString 方法相同,那么在代理实例上调用这样的方法时,传递到调用处理程序的 Method 对象将使 java.lang.Object 成为其声明类。换句话说,java.lang.Object 公共的非最终方法理论上在所有代理接口之前,以便确定哪一个 Method 对象传递到调用处理程序。
但是:这里的size( )方法用到了还是用到了Invocation对象中的invoke( )方法!!
哪位大侠能帮小弟解释清楚么?












评分

参与人数 1技术分 +1 收起 理由
菜小徐 + 1

查看全部评分

1 个回复

倒序浏览
代理类调用被代理类的某一个方法时,每一次调用都会在底层调用invoke方法,因为在invoke方法里面就会存放切面代码+目标方法
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马