對JDK動態代理的模擬
動態代理在JDK中的實作:
IProducer proxyProduec = (IProducer)Proxy.newProxyInstance(producer.getClass().getClassLoader()
, producer.getClass().getInterfaces(),new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue = https://www.cnblogs.com/wf614/p/null;
Float money = (Float)args[0];
if("saleProduct".equals(method.getName())){
rtValue = method.invoke(producer, money * 0.8f);
}
return rtValue;
}
});
來看看newProxyInstance()這個方法在JDK中的定義
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
...
}
它需要三個引數:
ClassLoader loader:類加載器,JDK代理中認為由同一個類加載器加載的類生成的物件相同所以要傳入一個加載器,而且在代理物件生成程序中也可能用到類加載器,
Class<?>[] interfaces:要被代理的類的介面,因為類可以實作多個介面,使用此處給的是Class陣列,
InvocationHandler h:代理邏輯就是通過重寫該介面的invoke()方法實作
通過對newProxyInstance()方法的分析我們能可以做出以下分析:
第二個引數Class<?>[] interfaces是介面陣列,那么為什么需要被代理類的介面?應該是為了找到要增強的方法,因為由JDK實作的動態代理只能代理有介面的類,
2.InvocationHandler h:引數通過重寫其invoke()方法實作了對方法的增強,我們先來看一下invoke()方法是如何定義的
/**
* 作用:執行的被代理物件的方法都會經過此方法
* @param proxy 代理物件的參考
* @param method 當前執行的方法的物件
* @param args 被代理物件方法的引數
* @return 被代理物件方法的回傳值
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
而想要重新該方法并完成對目標物件的代理,就需要使用method物件的invoke()方法(注:這個方法與InvocationHandler 中的invoke方法不同不過InvocationHandler 中的invoke方法主要也是為了宣告使用Method中的invoke()方法),我們在來看看Method中的invoke()方法
public Object invoke(Object obj, Object... args)
這里終于看到我們要代理的物件要寫入的位置,
對有以上內容,我們可以做出以下猜想:(說是猜想,但實際JDk的動態代理就是基于此實作,不過其處理的東西更多,也更加全面)
Proxy.newProxyInstance(..)這個方法的并不參與具體的代理程序,而是通過生成代理物件proxy來呼叫InvocationHandler 中的invoke()方法,通過invoke()方法來實作代理的具體邏輯,
所以我以下模擬JDK動態代理的這個程序,就是基于以上猜想實作,需要寫兩個內容,一個是生成代理物件的類(我命名為ProxyUtil),一個實作對代理物件的增強(我命名為MyHandler介面)
Proxy類
package wf.util;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class ProxyUtil {
/**
* public UserDaoImpl(User)
* @param targetInf
* @return
*/
public static Object newInstance(Class targetInf,MyHandler h){
Object proxy = null;
String tab = "\t";
String line = "\n";
String infname = targetInf.getSimpleName();
String content = "";
//這里把代理類的包名寫死了,但JDK實作的程序中會判斷代理的方法是否是public,如果是則其包名是默認的com.sun.Proxy包下,而如果方法型別不是public則生產的Java檔案包名會和要代理的物件包名相同,這是和修飾符的訪問權限有關
String packageName = "package com.google;"+line;
String importContent = "import "+targetInf.getName()+";"+line
+"import wf.util.MyHandler;"+line
+"import java.lang.reflect.Method;"+line;
//宣告類
String clazzFirstLineContent = "public class $Proxy implements "+infname+"{"+line;
//屬性
String attributeCont = tab+"private MyHandler h;"+line;
//構造方法
String constructorCont = tab+"public $Proxy (MyHandler h){" +line
+tab+tab+"this.h = h;"+line
+tab+"}"+line;
//要代理的方法
String mtehodCont = "";
Method[] methods = targetInf.getMethods();
for (Method method : methods) {
//方法回傳值型別
String returnType = method.getReturnType().getSimpleName();
// 方法名稱
String methodName = method.getName();
//方法引數
Class<?>[] types = method.getParameterTypes();
//傳入引數
String argesCont = "";
//呼叫目標物件的方法時的傳參
String paramterCont = "";
int flag = 0;
for (Class<?> type : types) {
String argName = type.getSimpleName();
argesCont = argName+" p"+flag+",";
paramterCont = "p" + flag+",";
flag++;
}
if (argesCont.length()>0){
argesCont=argesCont.substring(0,argesCont.lastIndexOf(",")-1);
paramterCont=paramterCont.substring(0,paramterCont.lastIndexOf(",")-1);
}
mtehodCont+=tab+"public "+returnType+" "+methodName+"("+argesCont+")throws Exception {"+line
+tab+tab+"Method method = Class.forName(\""+targetInf.getName()+"\").getDeclaredMethod(\""+methodName+"\");"+line;
if (returnType == "void"){
mtehodCont+=tab+tab+"h.invoke(method);"+line;
}else {
mtehodCont+=tab+tab+"return ("+returnType+")h.invoke(method);"+line;
}
mtehodCont+=tab+"}"+line;
}
content=packageName+importContent+clazzFirstLineContent+attributeCont+constructorCont+mtehodCont+"}";
// System.out.println(content);
//把字串寫入java檔案
File file = new File("D:\\com\\google\\$Proxy.java");
try {
if (!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
fw.write(content);
fw.flush();
fw.close();
//編譯java檔案
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
Iterable units = fileMgr.getJavaFileObjects(file);
JavaCompiler.CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
t.call();
fileMgr.close();
URL[] urls = new URL[]{new URL("file:D:\\\\")};
URLClassLoader urlClassLoader = new URLClassLoader(urls);
Class clazz = urlClassLoader.loadClass("com.google.$Proxy");
Constructor constructor = clazz.getConstructor(MyHandler.class);
proxy = constructor.newInstance(h);
}catch (Exception e){
e.printStackTrace();
}
return proxy;
}
}
該類會通過String字串生成一個java類檔案進而生成代理物件
補充: 我在實作Java檔案時把代理類的包名寫死了,但JDK實作的程序中會判斷代理的方法是否是public,如果是則其包名是默認的com.sun.Proxy包下,而如果方法型別不是public則生產的Java檔案包名會和要代理的物件包名相同,這是和修飾符的訪問權限有關
生成的java類為($Proxy)
package com.google;
import wf.dao.UserDao;
import wf.util.MyHandler;
import java.lang.reflect.Method;
public class $Proxy implements UserDao{
private MyHandler h;
public $Proxy (MyHandler h){
this.h = h;
}
public void query()throws Exception {
Method method = Class.forName("wf.dao.UserDao").getDeclaredMethod("query");
h.invoke(method);
}
public String query1(String p)throws Exception {
Method method = Class.forName("wf.dao.UserDao").getDeclaredMethod("query1");
return (String)h.invoke(method);
}
}
可以看到代理物件其實起一個中專作用,來呼叫實作代理邏輯的MyHandler介面
MyHandler實作如下:
package wf.util;
import java.lang.reflect.Method;
public interface MyHandler {
//這里做了簡化處理只需要傳入method物件即可
public Object invoke(Method method);
}
其實作類如下
package wf.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyHandlerImpl implements MyHandler {
Object target;
public MyHandlerImpl(Object target){
this.target=target;
}
@Override
public Object invoke(Method method) {
try {
System.out.println("MyHandlerImpl");
return method.invoke(target);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
這里對代理物件的傳入是通過構造方法來傳入,
至此模擬完成,看一下以下結果
package wf.test;
import wf.dao.UserDao;
import wf.dao.impl.UserDaoImpl;
import wf.proxy.UserDaoLog;
import wf.util.MyHandlerImpl;
import wf.util.MyInvocationHandler;
import wf.util.ProxyUtil;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) throws Exception {
final UserDaoImpl target = new UserDaoImpl();
System.out.println("自定義代理");
UserDao proxy = (UserDao) ProxyUtil.newInstance(UserDao.class, new MyHandlerImpl(new UserDaoImpl()));
proxy.query();
System.out.println("java提供的代理");
UserDao proxy1 = (UserDao) Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[]{UserDao.class},
new MyInvocationHandler(new UserDaoImpl()));
proxy1.query();
}
}
輸出:
自定義代理
MyHandlerImpl
查詢資料庫
------分界線----
java提供的代理
proxy
查詢資料庫
兩種方式都實作了代理,而實際上JDK的動態代理的主要思想和以上相同,不過其底層不是通過String來實作代理類的Java檔案的撰寫,而JDK則是通過byte[]實作,其生成Class物件時通過native方法實作,通過c++代碼實作,不是java要討論的內容,
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
private static native Class<?> defineClass0(ClassLoader loader, String name,
byte[] b, int off, int len);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/37790.html
標籤:設計模式
上一篇:設計模式-單例模式code
下一篇:設計模式------中介者模式
