Reloading Java Classes on the fly

Something that we needed to do for a project that I was working on was to be able to recompile a certain section of the code, and have it work next time it was called in the applicaiton, without needing to restart the JVM.

So after scouring the net I managed to come up with a solution. This definately works in jdk1.1, and I haven't seen any reason for it not to work in 1.2 and above.

Java classes themselves are dumped from memory when the classloader that loaded them is garbage collected. So the way to dynamically reload a class is to make sure that you control the classloader for that class. So when, all the references to instances of that class are gone, and you null the classloader itself, the runtime should collect the class itself. Then, next time an object of that class is used, it needs to be loaded again.

Sample Class Loader

The class above is used to load the required class. Below is a code snippet on how we loaded and constructed the classes in a factory method.

String className = "com.lib.class.ClassSpecial";
Object force = new Object();

try 
{
	Class loadClass = classLoader.loadClass(className);
	Class[] args = new Class[] {ThreadGroup.class, String.class, JXenoSnake.class, int.class, int.class, boolean.class};
	Constructor classCon = loadClass.getConstructor(args);
	force = classCon.newInstance(new Object[] {threadGroup, forces[type], parentSnake, new Integer(forceIndex), new Integer(frameNumber), new Boolean(prepare)});
}
catch (Exception e)
{
	System.out.println("Exception creating force : "+e);
	e.printStackTrace();
	return null;
}

Back to Java Index
Back to Start Page

Send me email