Update Java code during runtime

Various app containers can do this.

Basically you'd need to reload the class in a new ClassLoader (unless you're talking about doing this under the debugger, in which case there are completely different APIs available).

In my opinion, this kind of thing is rarely worth the hassle: designing everything so that it can be reloaded is considerably harder than designing it so it can be completely restarted in a new process. It's also easier to be sure exactly what code is running if there's only ever one version loaded in the process.

It's a neat thing to be able to demo, but for most applications it's not worth it. All in my opinion, of course :)

Note that one notable exception is the ability to reload web UI layers without restarting the container: that can make life much easier.


The HotSwap technology was added to Java 1.4 and enable class file replacement at run-time. The feature is provide through the redefineClasses method of the instrumentation package. I think you can also do that through the JPDA interface.

Here is also a reference to what I believe is the research paper that describe the HotSwap mechanism first:

  • Towards Flexible and Safe Technology for Runtime Evolution of Java Language Applications

Otherwise you can use Classloader, as the other mentionned, but it only provides dynamic class loading, not replacement. The same class loaded twice will be considered as two different types. Combined with interface and/or a bit of reflection, it can however provide ways to update the application at run-time.

Here is a reference to an awesome paper about class loader, and there usage:

  • Dynamic Class Loading in the Java Virtual Machine

I won't expand on whether this is good or bad, because it was not your question, but I think it's great to have support for run-time software evolution -- too bad that JSR-117 never made it!

Tags:

Java

Runtime