1. 程式人生 > >aop用代理實現

aop用代理實現

his @override row pri pack new eve and 實現

package com.atguigu.java;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Human1{
void info();
void fly();
}
//被代理類
class Superman1 implements Human1{

/* (non-Javadoc)
* @see com.atguigu.java.Human1#info()
*/
@Override
public void info() {
System.out.println("我是超人我怕誰");

}

/* (non-Javadoc)
* @see com.atguigu.java.Human1#fly()
*/
@Override
public void fly() {
System.out.println("i believe i can fly !");

}

}

class Humanutil1{
/**
* @author shanghaitao
* @since 2017年5月2日
*/
public void method1() {
System.out.println("------=方法一=-----");
}

/**
* @author shanghaitao
* @since 2017年5月2日
*/
public void method2() {
System.out.println("------=方法二=-----");
}

}


class MyinvacationHandlder1 implements InvocationHandler{

Object obj;
public void setObject(Object obj){
this.obj= obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Humanutil1 ht = new Humanutil1();
ht.method1();
Object oobj = method.invoke(obj, args);
ht.method2();
return oobj;
}

}

class Myproxy1{
/**
* @author shanghaitao
* @since 2017年5月2日
*/
public static Object getProxyInstance(Object obj) {
MyinvacationHandlder1 mh = new MyinvacationHandlder1();
mh.setObject(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), mh);

}
}

/**
*方法說明
* @author shanghaitao
* @since 2017年5月2日
*/
public class TestAOP1 {
public static void main(String[] args) {
Superman1 man = new Superman1();
Object obj = Myproxy1.getProxyInstance(man);
Human1 hu = (Human1)obj;
hu.info();
System.out.println();
hu.fly();


}
}

輸出

------=方法一=-----
我是超人我怕誰
------=方法二=-----

------=方法一=-----
i believe i can fly !
------=方法二=-----

aop用代理實現