zoukankan      html  css  js  c++  java
  • java中的动态代理----自己手动实现

    代码使用了common-io,需要其jar

    1 接口

    Java代码  收藏代码
    1. public interface Pruduct {  
    2.     void selling();  
    3. }  

     2 书籍类

    Java代码  收藏代码
    1. public class Book implements Pruduct {  
    2.     @Override  
    3.     public void selling() {  
    4.         try {  
    5.             Thread.sleep(1000);  
    6.             System.out.println("books selling.....");  
    7.         } catch (InterruptedException e) {  
    8.             e.printStackTrace();  
    9.         }  
    10.     }  
    11. }  

     3 定义日志类

    Java代码  收藏代码
    1. public class LogTranService{  
    2.   
    3.     public static void before(){  
    4.            
    5.         System.out.println("begin log...");  
    6.     }  
    7.   
    8.     public static void after(){  
    9.         System.out.println("finish log...");  
    10.     }  
    11.   
    12. }  

     4 定义时间类

    Java代码  收藏代码
    1. public class TimeTranService {  
    2.     static long bgn;  
    3.   
    4.     public static void before(){  
    5.         bgn = System.currentTimeMillis();  
    6.         System.out.println("begin time...  " + bgn);  
    7.     }  
    8.     public static void after(){  
    9.         long end = System.currentTimeMillis();  
    10.         System.out.println("end time...  " + (end-bgn));  
    11.     }  
    12.   
    13. }  

     5 定义InvocationHander 

    Java代码  收藏代码
    1. import java.lang.reflect.Method;  
    2.   
    3. public interface InvocationHander {  
    4.     public void invoke(Object o,Method m);  
    5. }  
    Java代码  收藏代码
    1. import java.lang.reflect.Method;  
    2. public class ProxyHander implements InvocationHander {  
    3.   
    4.     private Object target;  
    5.     public ProxyHander(Object target) {  
    6.         this.target = target;  
    7.     }  
    8.     @Override  
    9.     public void invoke(Object o, Method m) {  
    10.         try {  
    11.             TimeTranService.before();  
    12.             LogTranService.before();  
    13.             m.invoke(target);  
    14.             LogTranService.after();  
    15.             TimeTranService.after();  
    16.         } catch (Exception e) {  
    17.             e.printStackTrace();  
    18.         }   
    19.     }  
    20. }  

     6 代理类

    Java代码  收藏代码
    1. import java.io.File;  
    2. import java.io.IOException;  
    3. import java.lang.reflect.Constructor;  
    4. import java.lang.reflect.Method;  
    5.   
    6. import javax.tools.JavaCompiler;  
    7. import javax.tools.JavaCompiler.CompilationTask;  
    8. import javax.tools.StandardJavaFileManager;  
    9. import javax.tools.ToolProvider;  
    10.   
    11. import org.apache.commons.io.FileUtils;  
    12. public class Proxy {  
    13.     /* 
    14.      * 空的构造函数 
    15.      */  
    16.     private Proxy(){  
    17.     }  
    18.     /* 
    19.      * 返回代理类 
    20.      */  
    21.     public static Object newProxyInstance(Class inter,InvocationHander h){  
    22.         String proxyClassName = "$Proxy3";  
    23.         String packageName  = inter.getPackage().getName();  
    24.         String InHanderPackage = h.getClass().getPackage().getName();  
    25.         String rt = " ";// 换行  
    26.         String methodCode = "";  
    27.         for (Method method:inter.getMethods()) {  
    28.             methodCode+="   @Override"+rt+  
    29.               
    30.             "   public void "+ method.getName()+"() {"+rt+  
    31.             "       try{"+rt+  
    32.             "           Method method  = "+inter.getName()+".class.getMethod(""   
    33.             +           method.getName()+   "");"+rt+  
    34.             "           h.invoke(this,method);      "+rt+  
    35.             "       }catch(Exception e ){" +rt+  
    36.             "           e.printStackTrace();" +rt+  
    37.             "       }"+rt+  
    38.             "   }";  
    39.         }  
    40.         /* 
    41.          * 总的java代码 
    42.          */  
    43.         String javaCode=    
    44.         "package  "+packageName+";"+rt+  
    45.         "import "+InHanderPackage+".InvocationHander;"+rt+  
    46.           
    47.         "import java.lang.reflect.Method;"+rt+  
    48.         "public class "+proxyClassName+" implements "+inter.getName()+" {"+rt+  
    49.         "   public "+proxyClassName+"("+InHanderPackage+".InvocationHander h) {"+rt+  
    50.         "       super();"+rt+  
    51.         "       this.h = h;"+rt+  
    52.         "   }"+rt+  
    53.         "   private "+InHanderPackage+".InvocationHander h;"+rt+  
    54.         methodCode+rt+  
    55.         "}";  
    56.         /* 
    57.          *  生成java文件 
    58.          */  
    59.         // 生成文件路径  
    60.         String filename =  System.getProperty("user.dir")+"/bin/"+packageName+"/"+proxyClassName+".java";  
    61.         File file = new File(filename);  
    62.         try {  
    63.             System.out.println(filename);  
    64.             FileUtils.writeStringToFile(file, javaCode);// commons-io这个框架可以放很方便的操作文件  
    65.         } catch (IOException e) {  
    66.             e.printStackTrace();  
    67.         }  
    68.           
    69.           
    70.         // 编译  拿到编译器  
    71.         JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();  
    72.         // 文件管理  
    73.         StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);  
    74.         //获取文件  
    75.         Iterable units = fileMgr.getJavaFileObjects(filename);  
    76.           
    77.         // 编译任务  
    78.         CompilationTask t  = compiler.getTask(null, fileMgr, null, null, null, units);  
    79.         // call进行编译  
    80.         t.call();  
    81.         try {  
    82.             fileMgr.close();  
    83.         } catch (IOException e) {  
    84.             e.printStackTrace();  
    85.         }  
    86.           
    87.         // load到内存  
    88.         ClassLoader cl = ClassLoader.getSystemClassLoader();  
    89.         try {  
    90.             Class c = cl.loadClass(packageName+"."+proxyClassName);  
    91.             Constructor ctr = c.getConstructor(InvocationHander.class);  
    92.             System.out.println("代理类的名字为:"+c.getName()+"===========");  
    93.             return ctr.newInstance(h);  
    94.         } catch (Exception e) {  
    95.             e.printStackTrace();  
    96.         }  
    97.         return null;  
    98.     }  
    99. }  

     7 测试

    Java代码  收藏代码
    1. public class Client {  
    2.     public static void main(String[] args) {  
    3.         Book book = new Book();  
    4.         InvocationHander h = new ProxyHander(book);  
    5.         Pruduct m = (Pruduct)Proxy.newProxyInstance(Pruduct.class,h);  
    6.         m.selling();  
    7.     }  
    8. }  

    =============仅供参考============

  • 相关阅读:
    jQuery的父,子,兄弟节点查找方法
    我们的产品最终入驻淘宝服务市场
    iframe显示滚动栏
    自己定义控件三部曲之动画篇(十三)——实现ListView Item进入动画
    [叁]Pomelo游戏server编程分享 之 server结构与配置分析
    数列求和
    字节与字符_字节流与字符流_ASCII与Unicode_GB2312_GBK_GB18030_BIG-5
    Codeforces Round #257(Div. 2) B. Jzzhu and Sequences(矩阵高速幂)
    呼叫保持流程
    PDF转EPUB格式电子书经验总结
  • 原文地址:https://www.cnblogs.com/xm1-ybtk/p/5099325.html
Copyright © 2011-2022 走看看