JDK動態代理的一個最簡單的實例

JDK動態代理大家都知道的有spring aop,它的實現就是基於JDK的動態代理,它只能對實現了接口的類實現代理,在程序運行過程中,根據代理的接口來動態生成代理類,如果要使用類的代理,就得使用cglib,我們另一篇文章進行說明。下面直接看一個最簡單的實例代碼
1:定義一個接口
public interface IUser {
void addUser();
}
2:定義接口的實現
import com.common.service.IUser;
public class UserImpl implements IUser {
public void addUser() {
// 這裏是代碼邏輯,我們省略,只打印一句話,做爲演示
System.out.print("------------add user success----------");
}
}
3:實現代碼類
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.common.service.IUser;
import com.common.service.impl.UserImpl;
public class MyInvocation implements InvocationHandler {
private Object target;
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// 加入該對象執行之前的代碼邏輯,這裏我們只打印一句話,複雜的邏輯也是一樣加在這裏
System.out.print("對象執行之前的代碼邏輯");

// 返回代理對象
Object resultObject = method.invoke(target, args);

// 加入該對象執行之後的代碼邏輯,這裏我們只打印一句話,複雜的邏輯也是一樣加在這裏
System.out.print("對象執行之後的代碼邏輯");
return resultObject;
}
public MyInvocation(Object target) {
this.target = target;
}
}
4:測試代碼是否正常
// 測試方法,也可以寫在junit中
public static void main(String[] args) {
// 得到代理對象
MyInvocation myInvocationHandler = new MyInvocation(new UserImpl());
IUser proxy = (IUser) Proxy.newProxyInstance(MyInvocation.class.getClassLoader(),
new Class[] { IUser.class }, myInvocationHandler);
// 調用方法
proxy.addUser();
}
5:查看運行結果
對象執行之前的代碼邏輯------------add user success----------對象執行之後的代碼邏輯
發現在add方法執行前和執行後打印出來我們執行的代碼。這只是一個最簡單的實現,類似helloworld,如果有興趣的話,可以再進行深入研究 。瞭解一個最簡單的實現後再去研究會很有幫助的。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章