用Jdk实现AOP

 JDK1.2以后提供了动态代理的支持,通过实现java.lang.reflect.InvocationHandler接口提供一个执行处理器,然后通过java.lang.reflect.Proxy得到一个代理对象,通过这个代理对象来执行商业方法,在商业方法被调用的同时,执行处理器会被自动调用,从而实现方法拦截。nanning就是这样原理的,spring也用了动态代理作为实现之一。

动态代理定义:A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

可参看 http://java.sun.com/j2se/1.4.2/docs/guide/reflection/proxy.html

这是一个简单的例子:

接口:

public interface Foo {
     Object bar(Object obj) throws Exception;
}

一个简单实现:

public class FooImple implements Foo {

    public Object bar(Object obj) throws Exception {
       System.out.println("method executing ...");
       return obj;
    }
}

代理类:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DebugProxy implements java.lang.reflect.InvocationHandler {

    private Object obj;
    public static Object newInstance(Object obj) {
       return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
        obj.getClass().getInterfaces(), new DebugProxy(obj));
    }

    private DebugProxy(Object obj) {
       this.obj = obj;
    }

    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {

       Object result;
       try {
           //System.out.println("proxy is  " + proxy.getClass().getName());
           System.out.println("before method " + m.getName());
           result = m.invoke(obj, args);
       } catch (InvocationTargetException e) {
           throw e.getTargetException();
       } catch (Exception e) {
           throw new RuntimeException("unexpected invocation exception: "
                 + e.getMessage());
       } finally {
           System.out.println("after method " + m.getName());
       }
       return result;
    }

}

测试类:

public class test { 

    public static void main(String[] args) throws Exception {

       Foo foo = (Foo) DebugProxy.newInstance(new FooImple());
       foo.bar(new String("test"));

    }

}

测试结果:

D:y>java -classpath . test
before method bar
method executing ...
after method bar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值