需求:
有两个固定的方法,method1和method2,需要在method1和method2种插入不同的代码,为了减少代码的复用,可以使用动态代理的方式实现(当然也可以在每段代码前面都插入method1和method2,但是这种办法显得很笨拙)
结构图:
通过动态代理方法实现的aop代码:
只要通过myProxy 建立的代理类对象在调用被代理类方法时都会在开头和结尾插入method1和method2
package D19.AOP;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @Author: wj
* @Date: 2018/12/2 14:52
* @Version 1.0
*/
interface Human{
void info();
void fly();
}
//被代理类
class SuperMan implements Human{
public void info() {
System.out.println("SuperMan info");
}
public void fly() {
System.out.println("superMan fly");
}
}
//进行aop操作的类,要求在method1与method2间插入被代理类的方法
class HumanUtil{
public void method1(){
System.out.println("=====method1======");
}
public void method2(){
System.out.println("======method2=======");
}
}
//代理类
class MyInvocationHandler implements InvocationHandler{
Object object;
public void setObject(Object object) {
this.object = object;
}
//在methoo1与method2之间插入被代理类方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
HumanUtil util = new HumanUtil();
util.method1();
Object returnVal = method.invoke(object,args);
util.method2();
return returnVal;
}
}
class myProxy{
//动态创建代理类对象
public static Object getProxyInstance(Object obj){
//创建代理类对象
MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
myInvocationHandler.setObject(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),myInvocationHandler);
}
}
public class TestAop {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();//被代理类对象
Object obj = myProxy.getProxyInstance(superMan);//代理类对象
Human human = (Human) obj;
human.info();
System.out.println();
human.fly();
}
}
结果: