首先编写一个生成代理主题角色的类:Proxy - package com.gjy.DynamicProxy;
- public class Proxy {
- public static Object newProxyIntenct(Class infac,InvocationHandler h) throws Exception{
- String br ="\r\n";
- String methString ="";
- Method[] method = infac.getMethods();
- for(Method m: method){
- methString = " @Override"+ br +
- " public void "+m.getName()+"() {"+ br +
- " try {" + br +
- " Method md ="+ infac.getName()+".class.getMethod(\""+m.getName()+"\");"+ br +
- " h.invoke(this,md);" + br +
- " }catch (Exception e){ "+ br+
- " e.printStackTrace();" + br +
- " }" + br +
- " }";
- }
- String src = "package com.gjy.DynamicProxy;" + br +
- "import java.lang.reflect.Method;" + br +
- "public class $Proxy implements "+infac.getName()+"{" + br +
- " private com.gjy.DynamicProxy.InvocationHandler h;" + br +
- " public $Proxy(InvocationHandler h) {" + br +
- " super();" + br +
- " this.h = h;" + br +
- " }" + br + br +
- methString +br +
- "}";
- MakFileUtil.createFile("D:/src/com/gjy/DynamicProxy");
- //生成java文件
- String fileName ="D:\\src\\com\\gjy\\DynamicProxy\\$Proxy.java";
- System.out.println(fileName);
- File file = new File(fileName);
- FileWriter fWriter = new FileWriter(file);
- fWriter.write(src);
- fWriter.flush();
- fWriter.close();
- //生成class文件,jdk6提供的工具类
- JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
- //System.out.println(compiler.getClass().getName());
- StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
- Iterable units = fileManager.getJavaFileObjects(fileName);
- CompilationTask task = compiler.getTask(null, fileManager, null, null, null, units);
- task.call();
- fileManager.close();
- //装载到内存,生成新对象
- URL[] urls = new URL[]{new URL("file:/"+"D:\\src\\")};
- URLClassLoader loader = new URLClassLoader(urls);
- Class c = loader.loadClass("com.gjy.DynamicProxy.$Proxy");
- //通过有参的构造器反射生成代理类的实例
- Constructor ctr = c.getConstructor(InvocationHandler.class);
- Object obj = (Object) ctr.newInstance(h);
- return obj;
- }
- }
复制代码 代理对象的操作接口: - package com.gjy.DynamicProxy;
- public interface InvocationHandler {
- void invoke(Object o,Method m);
- }
复制代码 通过实现代理对象的操作接口实现对被代理对象的方法调用前后的逻辑操作。
TimeInvocationHandler实现InvocationHandler接口: - package com.gjy.DynamicProxy;
- public class TimeInvocationHandler implements InvocationHandler {
- private Object target;
- public TimeInvocationHandler(Object target) {
- this.target = target;
- }
- @Override
- public void invoke(Object o, Method m) {
- long time1 = System.currentTimeMillis();
- System.out.println("time1="+time1);
- try {
- m.invoke(target);
- } catch (Exception e) {
- e.printStackTrace();
- }
- long time2 = System.currentTimeMillis();
- System.out.println("time2="+time2);
- System.out.println("Tank 的启动时间:"+(time2-time1));
复制代码 实际被代理对象:Tank - package com.gjy.DynamicProxy;
- public class Tank implements Moveable{
- @Override
- public void move() {
- int a = 5;int b = 6;int c = 0; int d = 0;
- for (int i = 0; i < 1000; i++) {
- d = i;
- }
- c = ((a+b)/2)*12;
- System.out.println("TanK moving..Tank 的速度是"+c);
- }
复制代码 抽象代理主题:Moveable - package com.gjy.DynamicProxy;
- public interface Moveable {
- void move();
- }
- }
复制代码 测试: - package com.gjy.DynamicProxy;
- public class TestTank {
- public static void main(String[] args) throws Exception{
- Tank t = new Tank();
- Moveable moveable = (Moveable) Proxy.newProxyIntenct(Moveable.class,new TimeInvocationHandler(t));
- moveable.move();
- }
- }
复制代码 创建文件夹工具类:MakFileUtil - package com.gjy.DynamicProxy;
- public class MakFileUtil {
- public static void createFile(String pathstr) throws IOException{
- //创建多级目录
- String path = pathstr;
- //为指定字符串构造一个 string tokenizer。 "/"字符是分隔标记的分隔符。分隔符字符本身不作为标记。
- StringTokenizer st = new StringTokenizer(path,"/");
- String path1 = st.nextToken()+"/";
- String path2 = path1;
- while(st.hasMoreTokens())
- {
- path1 = st.nextToken()+"/";
- path2 += path1;
- File inbox = new File(path2);
- if(!inbox.exists())
- inbox.mkdir();
- }
- }
- }
复制代码 以上就是动态代理的一个模拟实现,测试时我们不管Proxy和InvocationHandler是怎么实现的,我们只要实现InvocationHandler接口完成相应的逻辑,然后调用Proxy
的newProxyIntenct(Class infac, InvocationHandler h) 传入相应的接口,和InvocationHandler的实现类就可以实现对被代理对象的代理。也就是说Proxy和InvocationHandler写好之后永远不变。
在运行过程中Proxy会动态生成代理主题角色,示例中生成的代理主题角色的代码如下: - public class $Proxy implements com.gjy.DynamicProxy.Moveable{
- private com.gjy.DynamicProxy.InvocationHandler h;
- public $Proxy(MakFileUtil h) {
- super();
- this.h = h;
- }
- @Override
- public void move() {
- try {
- Method md =com.gjy.DynamicProxy.Moveable.class.getMethod("move");
- h.invoke(this,md);
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
复制代码 如果我们想在Tank的move()方法被调用的前后加入其它的逻辑处理,我们只需实现InvocationHandler接口,下面是给move()加日志: - package com.gjy.DynamicProxy;
- public class LogInvocationHandler implements InvocationHandler {
- private Object target;
- public LogInvocationHandler(Object target) {
- this.target = target;
- }
- @Override
- public void invoke(Object o, Method m) {
- System.out.println("Tank start...........");
- try {
- m.invoke(target);
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("Tank stop..............");
- }
- }
复制代码 测试: - package com.gjy.DynamicProxy;
- public class TestTank {
- public static void main(String[] args) throws Exception{
- Tank t = new Tank();
- Moveable moveable = (Moveable) Proxy.newProxyIntenct(Moveable.class,new TimeInvocationHandler(t));
- Moveable moveable2 = (Moveable) Proxy.newProxyIntenct(Moveable.class, new LogInvocationHandler(moveable));
- moveable2.move();
- }
- }
复制代码 |