- package cn.itcast.day3;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- import java.util.ArrayList;
- import java.util.Collection;
- public class ProxyTest {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception{
- // TODO Auto-generated method stub
- Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
- final ArrayList target = new ArrayList();
- Collection proxy3 = (Collection)getProxy(target,new MyAdvice());
- proxy3.add("zxx");
- proxy3.add("lhm");
- proxy3.add("bxd");
- System.out.println(proxy3.size());
- System.out.println(proxy3.getClass().getName());
- }
- private static Object getProxy(final Object target,final Advice advice) {
- Object proxy3 = Proxy.newProxyInstance(
- target.getClass().getClassLoader(),
- /*new Class[]{Collection.class},*/
- target.getClass().getInterfaces(),
- new InvocationHandler(){
-
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- /*long beginTime = System.currentTimeMillis();
- Object retVal = method.invoke(target, args);
- long endTime = System.currentTimeMillis();
- System.out.println(method.getName() + " running time of " + (endTime - beginTime));
- return retVal;*/
-
- advice.beforeMethod(method);
- Object retVal = method.invoke(target, args);
- advice.afterMethod(method);
- return retVal;
-
- }
- }
- );
- return proxy3;
- }
- }
- package cn.itcast.day3;
- import java.lang.reflect.Method;
- public interface Advice {
- void beforeMethod(Method method);
- void afterMethod(Method method);
- }
- package cn.itcast.day3;
- import java.lang.reflect.Method;
- public class MyAdvice implements Advice {
- long beginTime = 0;
- public void afterMethod(Method method) {
- // TODO Auto-generated method stub
- System.out.println("从传智播客毕业上班啦!");
- long endTime = System.currentTimeMillis();
- System.out.println(method.getName() + " running time of " + (endTime - beginTime));
- }
- public void beforeMethod(Method method) {
- // TODO Auto-generated method stub
- System.out.println("到传智播客来学习啦!");
- beginTime = System.currentTimeMillis();
- }
- }
复制代码 请问一下,add()方法是怎样调用代理的,请详细介绍一下这之间的过程,一直搞不明白是这之间是怎样传递的 |
|