需求:
有兩個固定的方法,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();
}
}
結果: