AOP现在很多框架都有这个功能,但是java自身也有这个功能,只不过要自己进行一下手动编写,才能够实现,不过其原理都差不多。
起重要用的java类包有
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
其实现原理大概是这样,
1.编写代理处理函数 其必须事先java.lang.reflect.InvocationHandler接口
2.首先写一个接口
3.编写实现此接口的方法
5.编写客户端程序
Let'S go!
for example:
第一步,编写代理处理类
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- public class Handler implements InvocationHandler{
- private Object obj;
- public Object bind(Object obj){
- this.obj=obj;
- return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
- obj.getClass.getInterfaces(),this)
- }
- public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{
- System.out.println("began");
- Object result=method.invoke(this.obj,obj);
- System.out.println("after");
- return result;
- }
- }
第二步,写接口
- public interface IHello {
- public void toHello(String name);
- }
第三步,实现接口
- public class HelloImp implements SayHello{
- public void toHello(String name) {
- System.out.println("hello:" + name);
- }
- }
第四步,客户端调用
- public class ProxyDemo {
- public static void main(String[] args) throws SecurityException, NoSuchMethodException {
- LogHandler logHandler = new LogHandler();
- SayHello hello = (SayHello)logHandler.bind(new HelloImp());
- hello.toHello("hello");
- }
- }