简体   繁体   English

如何使用URLClassLoader重新加载已更改的类文件

[英]How to reload a changed class file by using the URLClassLoader

I am developing a smartcard tester. 我正在开发智能卡测试仪。 The test case script files are written in java. 测试用例脚本文件是用Java编写的。 In this tester, I have editors for editing the test case files. 在这个测试人员中,我有用于编辑测试用例文件的编辑器。 After editing, these files should be able to be compiled, loaded and instantiated. 编辑之后,这些文件应该能够被编译,加载和实例化。

I have finished the compilation work by using the JavaCompiler. 我已经使用JavaCompiler完成了编译工作。 The problem is about the loading. 问题是关于加载。 I used the URLClassLoader.newInstance to get a URLCLassLoader object and load my .class dynamically on the fly. 我使用URLClassLoader.newInstance来获取URLCLassLoader对象,并动态地动态加载.class。 It works well except that it wouldn't reload the class file even if the case file has been edited and compiled. 它运行良好,除了即使案例文件已被编辑和编译也不会重新加载类文件。 It use the old version of the class file and give the old result. 它使用类文件的旧版本并给出旧结果。 It loads the new class file only if i restart the tester. 仅当我重新启动测试仪时,它才会加载新的类文件。

Is there a way for me to control the reloading of class files by using the URLClassLoader? 有没有一种方法可以通过使用URLClassLoader来控制类文件的重新加载?

Thanks a lot. 非常感谢。

在编辑器的保存操作中,调用加载类方法。

Once a class has been loaded, you generally can't modify that class instance. 加载类后,通常无法修改该类实例。 The only options are: 唯一的选择是:

  1. Create a new class loader, load a new copy of the class, and update all references to the old version of the class and any instances of the class. 创建一个新的类加载器,加载该类的新副本,并将所有引用更新到该类的旧版本以及该类的任何实例。 This can be difficult, which is why class loader memory leaks occur in application server environments. 这可能很困难,这就是为什么在应用程序服务器环境中发生类加载器内存泄漏的原因。

  2. Use JVMTI or Instrumentation to redefine the class bytes of an already loaded class. 使用JVMTI或Instrumentation重新定义已加载类的类字节。 I'm not as familiar with JVMTI, but the Instrumentation.redefineClasses method has many restrictions: 我对JVMTI不太熟悉,但是Instrumentation.redefineClasses方法有很多限制:

The redefinition may change method bodies, the constant pool and attributes. 重新定义可能会更改方法主体,常量池和属性。 The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. 重新定义不得添加,删除或重命名字段或方法,更改方法的签名或更改继承。 These restrictions maybe be lifted in future versions. 这些限制可能会在将来的版本中取消。 The class file bytes are not checked, verified and installed until after the transformations have been applied, if the resultant bytes are in error this method will throw an exception. 在应用转换之后,才检查,验证和安装类文件字节,如果结果字节错误,则此方法将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM