您当前的位置: 首页 >  I.T10001 jvm

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

I.T10001 发布时间:2020-01-11 16:10:49 ,浏览量:3

自定义类加载器

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());

}

}

关注
打赏
1688896170
查看更多评论

I.T10001

暂无认证

  • 3浏览

    0关注

    154博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0475s