标签:style blog http io color ar os java sp
1、热部署是什么?
1 package com.csair.soc.hotswap; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 /** 6 * 自定义类加载器,并override findClass方法 7 */ 8 public class MyClassLoader extends ClassLoader{ 9 @Override 10 public Class<?> findClass(String name) throws ClassNotFoundException{ 11 try{ 12 String fileName = name.substring(name.lastIndexOf("." )+1) + ".class" ; 13 InputStream is = this.getClass().getResourceAsStream(fileName); 14 byte[] b = new byte[is.available()]; 15 is.read(b); 16 return defineClass(name, b, 0, b. length); 17 } catch(IOException e){ 18 throw new ClassNotFoundException(name); 19 } 20 } 21 }
1 package com.csair.soc.hotswap; 2 public class HelloWorld { 3 public void say(){ 4 System. out.println( "Hello World V1"); 5 } 6 }
1 package com.csair.soc.hotswap; 2 public class HelloWorld { 3 public void say(){ 4 System. out.println( "Hello World V2"); 5 } 6 }
1 package com.csair.soc.hotswap; 2 3 import java.io.File; 4 import java.lang.reflect.Method; 5 6 public class Hotswap { 7 public static void main(String[] args) throws Exception { 8 loadHelloWorld(); 9 // 回收资源,释放HelloWorld.class文件,使之可以被替换 10 System. gc(); 11 Thread. sleep(1000);// 等待资源被回收 12 File fileV2 = new File( "HelloWorld.class"); 13 File fileV1 = new File( 14 "bin\\com\\csair\\soc\\hotswap\\HelloWorld.class" ); 15 fileV1.delete(); //删除V1版本 16 fileV2.renameTo(fileV1); //更新V2版本 17 System. out.println( "Update success!"); 18 loadHelloWorld(); 19 } 20 21 public static void loadHelloWorld() throws Exception { 22 MyClassLoader myLoader = new MyClassLoader(); //自定义类加载器 23 Class<?> class1 = myLoader 24 .findClass( "com.csair.soc.hotswap.HelloWorld");//类实例 25 Object obj1 = class1.newInstance(); //生成新的对象 26 Method method = class1.getMethod( "say"); 27 method.invoke(obj1); //执行方法say 28 System. out.println(obj1.getClass()); //对象 29 System. out.println(obj1.getClass().getClassLoader()); //对象的类加载器 30 } 31 }
标签:style blog http io color ar os java sp
原文地址:http://www.cnblogs.com/pfxiong/p/4070462.html