Is it possible to reload class bytecode implementation in a classloader somehow? I'm trying to add a method to a class in runtime.
-
not sure but i think it can help.http://stackoverflow.com/questions/6680674/can-a-java-class-add-a-method-to-itself-at-runtime – kaysush Feb 25 '13 at 16:35
-
also [this could help](http://stackoverflow.com/questions/4016305/how-to-emit-and-execute-java-bytecode-at-runtime), particularly the accepted answer. I'm thinking something with [this](http://asm.ow2.org/) will do the trick – Stephen Feb 25 '13 at 17:40
1 Answers
No, you cannot reload a class, in any class loader.
What you can do is write and use a custom class loader that will load the first version of the class. When you want to update the class, you dispose of every instance of the first class, every instance of its Class<> object, and of the class loader that loaded the first version. This is the only way to unload a class in the JVM -- it will be unloaded when the GC collects all those things (instances of the class, of the Class<> object and of the ClassLoader that loaded the class).
Then, you instantiate a new class loader and load your class.
This is similar to what Servlet Containers -- Tomcat, for instance -- do to dynamically load and unload applications.
If you are just trying to add methods dynamically, there's a similar, very interesting, approach, that I used some time ago: you can use the Java Compiler API associated with a class loader. You pass the "code" of the class to your class loader, it will invoke the Java Compiler (in memory if you want: you won't need any files written on disk), and use the class loader to load the compiled bytecode. In any case, if you wish to unload classes loaded like this, you will have to discard the class loader, exactly as I described above.

- 37,201
- 11
- 119
- 156