jvm类加载机制实现热部署示例(1)

自定义类加载器

public class MyClassLoader extends ClassLoader {

 

@Override

protected Class<?> findClass(String name) throws ClassNotFoundException {

try {

// 文件名称

String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";

// 获取文件输入流

InputStream is = this.getClass().getResourceAsStream(fileName);

// 读取字节

byte[] b = new byte[is.available()];

is.read(b);

// byte字节流解析成jvm能够识别的Class对象

return defineClass(name, b, 0, b.length);

} catch (Exception e) {

throw new ClassNotFoundException();

}

 

}

 

}

更新类代码

public class Hotswap {

 

public static void main(String[] args)

throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,

SecurityException, IllegalArgumentException, InvocationTargetException, InterruptedException {

loadUser();

System.gc();

Thread.sleep(1000);// 等待资源回收

// 需要被热部署的class文件

File file1 = new File("F:\\test\\User.class");

// 之前编译好的class文件

File file2 = new File(

"F:\\itmayiedujiangke2018-02-24\\itmayiedu_itmayiedu_day_17\\target\\classes\\com\\itmayiedu\\User.class");

boolean isDelete = file2.delete();// 删除旧版本的class文件

if (!isDelete) {

System.out.println("热部署失败.");

return;

}

file1.renameTo(file2);

System.out.println("update success!");

loadUser();

}

 

public static void loadUser() throws ClassNotFoundException, InstantiationException, IllegalAccessException,

NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {

MyClassLoader myLoader = new MyClassLoader();

Class<?> class1 = myLoader.findClass("com.itmayiedu.User");

Object obj1 = class1.newInstance();

Method method = class1.getMethod("add");

method.invoke(obj1);

System.out.println(obj1.getClass());

System.out.println(obj1.getClass().getClassLoader());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值