本帖最后由 兜兜转转 于 2013-9-16 07:22 编辑
- <P>import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- public class MyHandler implements InvocationHandler
- {
- Object target ;
- Advice advice ;
- public MyHandler(Object target , Advice advice )
- {
- this.target = target;
- this.advice = advice;
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable
- {
- advice.beforDo(method);
- //这里执行方法不是要在Object proxy对象上执行吗?为什么往往都是在目标对象上执行呢?
- Object retval = method.invoke(target , args);
- advice.afterDo(method);
- return retval;
- }
- public Object getDynamicProxy()
- {
- return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),this );
- }
- }</P>
复制代码- import java.lang.reflect.InvocationHandler;
- import java.util.ArrayList;
- import java.util.List;
- public class MyDynamicTest
- {
- public static void main(String[] args)
- {
- List<String> list = new ArrayList<String>();
- Advice advice = new MyAdvice();
- MyHandler handler = new MyHandler(list, advice);
- List<String> listProxy = ( List)handler.getDynamicProxy();
- listProxy.add("Ansen");
- listProxy.add("Kaka1 SB");
- listProxy.add("Rudy SB");
- System.out.println( listProxy.size());
- }
- }
复制代码- import java.lang.reflect.Method;
- public interface Advice
- {
- public abstract void beforDo(Method m);
- public abstract void afterDo(Method m);
- }
复制代码- import java.lang.reflect.Method;
- public class MyAdvice implements Advice
- {
- long startTime = 0;
- @Override
- public void beforDo(Method m)
- {
- System.out.println(m.getName()+"方法开始执行!");
- startTime = System.currentTimeMillis();
- }
- @Override
- public void afterDo(Method m)
- {
- long endTime =System.currentTimeMillis();
- System.out.println();
- System.out.println(m.getName()+"方法执行结束! 执行用时为:"+(endTime-startTime));
- }
- }
复制代码 问题一:
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
advice.beforDo(method);
//这里执行方法正常不是要在Object proxy对象上执行吗?为什么往往都是在目标对象上执行呢?
Object retval = method.invoke(target , args);
advice.afterDo(method);
return retval;
}
为什么不写成这种格式:
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
advice.beforDo(method);
Object retval = method.invoke(proxy , args);----->会导致死循环?为什么?
advice.afterDo(method);
return retval;
}
问题二:
protected | Proxy(InvocationHandler h)
使用其调用处理程序的指定值从子类(通常为动态代理类)构建新的 Proxy 实例。 | Proxy这个类不不抽象类,构造方法也不是私有,是不是代表它可以创建对象?protected修饰的成员是可以被子类访问的,不是吗?
|
|