Can I reload the class with new bytecode?

Is it possible to somehow reload the implementation of the bytecode class in classloader? I am trying to add a method to a class at runtime.

+4
source share
1 answer

No, you cannot reload a class in any classloader.

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 a class, you delete every instance of the first class, every instance of the Class <> object and the class loader loading the first version. This is the only way to unload the class in the JVM - it will be unloaded when the GC collects all these things (instances of the class, class <> object and ClassLoader that loaded the class).

Then you instantiate a new class loader and load your class.

It looks like Servte Containers - Tomcat, for example - performs dynamic loading and unloading of applications.

If you are just trying to dynamically add methods, there is a similar, very interesting approach that I used some time ago: you can use the Java compiler API associated with the class loader. You pass the β€œcode” of the class to your class loader, it will call the Java Compiler (in memory, if you want: you do not need the files written to disk), and use the class loader to load the compiled byte code. In any case, if you want to unload classes loaded in this way, you will have to abandon the class loader, as I described above.

+2
source

All Articles