`
lihong11
  • 浏览: 450590 次
  • 性别: Icon_minigender_2
  • 来自: 湖南
社区版块
存档分类
最新评论
阅读更多

花了三天时间终于把马士兵的动态代理看完了,这是我做的一些笔记,附件是我按照他讲的思路写的代码。

1、JDK的实现

(1)把类写在一个字符串变量里,注意格式,这个字符串写在static Object newProxyInstance类中;

(2)用System.getProperty("u痵er.dir")来获得当前目录路径;

(3)把字符串写入到文件中;

(4)拿到编译器:JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(),注意compiler生成器是在jdk包下;

(5)拿到标准文件管理:StandardJavaFileManager sjfmgr = compiler.getStandardFileManager(null, null, null);

(6)拿到所有文件对象:Iterable iterable = sjfmgr.getJavaFileObjects(path);

(7)拿到编译任务:CompilationTask task = compiler.getTask(null, sjfmgr, null, null, null, iterable),用call()完成编译;

 

2.JDK的动态代理:不用修改原来的代码就能在原来的代码前后插入内容,比如AOP,主要用来做日志、事务、权限

(8)把硬盘中的类放到内存中去;

(9)根据路径拿到class的文件:URL[] urls = new URL[]{new URL("file:/"+System.getProperty("user.dir")+"/src")};

URLClassLoader urlClassLoader = new URLClassLoader(urls);

加载某个类: Class class1 = urlClassLoader.loadClass("com.proxy.TankTimeProxy");

(10)获得有某个参数类型的构造方法:Constructor constructor = class1.getConstructor(Moveable.class);

(11)产生一个对象,并把参数传过去:Moveable moveable = (Moveable) constructor.newInstance(new Tank());

 

(12)把接口活用;public static Object newProxyInstance(Class inf)

(13)拿到接口中的所有方法:Method [] methods = Moveable.class.getMethods();

for (Method m : methods) {

System.out.println(m.getName());

}

(14)创建一个接口类,并被实现;

(15)把接口作为参数传到newProxyInstance类中;

(16)定义一个target对象,并应用到invoke中;这时可以对任意的对象、接口方法实现任意的代理;

(17)测试类中实例化new TimeHandler;

 

测试自己写的代理:

(1)写一个UserMgrInf接口并定义一个addUser方法,一个UserMgr类实现UserMgrInf接口中的方法;

(2)写一个TransactionHandler类并实现InvocationHandler接口中的invoke方法;

(3)写一个测试类;

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics