user2401232
user2401232

Reputation: 27

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. 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. The problem is about the loading. I used the URLClassLoader.newInstance to get a URLCLassLoader object and load my .class dynamically on the fly. 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?

Thanks a lot.

Upvotes: 0

Views: 969

Answers (2)

Brett Kail
Brett Kail

Reputation: 33936

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. I'm not as familiar with JVMTI, but the Instrumentation.redefineClasses method has many restrictions:

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.

Upvotes: 0

Ninad Pingale
Ninad Pingale

Reputation: 7069

On save action of your editor, call your load class method.

Upvotes: 0

Related Questions