实现简单的代码热替换
2016-09-08 19:24
239 查看
package com.hotswap; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * Created by huangzhw on 2016/9/8. */ public class HotSwapTest { public static void main(String[] args) throws Exception{ while(true){ HotSwapClassLoader hotSwapClassLoader = new HotSwapClassLoader(); //所有在M类中所用到的类,都会通过HotSwapClassLoader进行加载 //加载时先调用loadClass(在LoadClass中定义,默认支持双亲委派),使用父加载器向上加载。 //只有所有父加载器都加载失败时,才调用findClass加载并生成类!!! //由于双亲委派的存在,所以对于自加载的类可以通过反射使用,也可以通过接口使用(接口类会由SystemClassLoader加载),在子类中加载接口时,会返回SystemClassLoader加载的对象。 Class<?> cls = hotSwapClassLoader.findClass("M"); Object target = cls.newInstance(); cls.getDeclaredMethod("prt").invoke(target); Thread.sleep(5000); } } private static class HotSwapClassLoader extends ClassLoader{ @Override protected Class<?> findClass(String name) throws ClassNotFoundException { File f = new File("D:\\M.class"); long size = f.length(); byte[] bs = new byte[(int)size]; try(FileInputStream fins = new FileInputStream(f)){ fins.read(bs); }catch (IOException ie){ System.out.println(ie); } return defineClass(name, bs, 0, (int)size); } } }
相关文章推荐
- 一行代码实现一个简单的模板字符串替换
- 简单SNMP管理程序的VC++代码实例实现
- 使用J2ME技术实现简单的动画(附代码实现)
- 基于web的QQ实现代码(asp) ——在网叶(web)上实现简单QQ功能(转)
- PHP实现的简单日历代码
- PHP实现的简单日历代码
- 内容分页简单实现代码及祥解(C#)
- 简单SNMP管理程序的VC++代码实例实现
- CSS实现简单的图片防盗链代码
- AjaxPanel自定义控件实现页面无刷新数据交互(做了个示例程序, 效果确实比较Cool, 用法非常简单! )(示例代码下载)
- C#实现数据库事务处理的简单示例代码
- J2ME 3D学习笔记——实现简单的界面(附代码)
- 图片切换效果Xhtml简单实现,一句代码搞定!
- 分形介绍 && 一个简单的Kotch curve实现代码
- 一个简单的态机模式工作流演示(2)(代码与实现)
- 简单代码,实现快速判断几个EDIT是否允许为空
- 内容分页简单实现代码及祥解(C#)
- 一个简单的AJAX实现,基于C#的ASP.Net,包括服务器端的程序代码
- 用简单的代码来实现文件上传
- asp下实现替换远程文件为本地文件并保存远程文件的代码