请教java的aop的原理,尤其是为什么调用业务方法的时候,会跑到invoke方法里面,谁知道的?public class ProxyDemo
{
public static void main(String[] args) throws SecurityException, NoSuchMethodException
{
LogHandler logHandler = new LogHandler();
IHello hello = (IHello) logHandler.bind(new HelloImp());
hello.toHello("hej"); 
                  // toHello()是业务方法,但是很奇怪,通过单步调试发现,他其实执行的是invoke()这个方法。
}
}下面是代理类import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public class LogHandler implements InvocationHandler
{ private Object deledate; public Object bind(Object deledate)
{
this.deledate = deledate;
return Proxy.newProxyInstance(deledate.getClass().getClassLoader(), deledate.getClass().getInterfaces(), this);
} /**
 * 
 */
public Object invoke(Object proxy, Method method, Object[] obj) throws Throwable
{
doBefore(); Object result = method.invoke(deledate, obj); doAfter(); return result;
} private void doBefore()
{
System.out.println("before....");
} private void doAfter()
{
System.out.println("after....");
}
//接口类
public interface IHello
{
public void toHello(String name);
}
//实现类
public class HelloImp implements IHello
{ public void toHello(String name)
{
System.out.println("hello:" + name);
}}

解决方案 »

  1.   

    因为你使用了InvocationHandler 
    下面是JDK文档中的原话:
    InvocationHandler 是代理实例的调用处理程序 实现的接口。 每个代码实例都具有一个关联的调用处理程序。对代理实例调用方法时,将对方法调用进行编码并将其指派到它的调用处理程序的 invoke 方法
      

  2.   

    结果是:
    before....
    hello:hej
    after....通过:
    return Proxy.newProxyInstance(deledate.getClass().getClassLoader(), deledate.getClass().getInterfaces(), this);
    这句话生成了HelloImp类的代理,以后在执行HelloImp类的方法时,都会先走到代理类的invoke方法。这就是proxy的原理。
      

  3.   

    说错了,应该是:通过
    return Proxy.newProxyInstance(deledate.getClass().getClassLoader(), deledate.getClass().getInterfaces(), this); 
    这句话生成了HelloImp类的代理,以后在执行HelloImp类的方法时,都会先走到代理类指定的处理类的的invoke方法。