How to use a patch jar to override existing Java class files temporarily
Suppose you have a large application running in production. A production issue has been reported to you. You are not sure what the problem is. You want to add some log statements to the code. Perhaps you want to try out a small fix too – a 3 line change in the code of a single Java file. How would you go about using the logging code or the updated class file in your app? You don’t want to go through a complex and formal “Install” procedure for your new version.
One way to do this is –
Make the code changes in your Eclipse workspace (or whatever IDE you use). Use the ‘Export as Jar’ option for the changed source file(s) – export only the compiled class files. Eclipse will put them in the appropriate package structure. Add the the jar onto the beginning of your classpath – how to do this will depend on your application. The easiest way is to just drop it into the $JAVA_HOME\lib\ext folder – the CLASSPATH won’t matter then.
Or you could try something from this list that works for you -
- Modify a start script.
- Change an environment variable.
- Add to a properties file.
- Maybe change a Jar file manifest.
Of course, you’ll also need to restart your app. Hot-Swapping is also a possibility – that doesn’t need a restart to update classes in many cases. And Java Rebel brings to the table a much more powerful form of Hot-Swapping that requires far fewer restarts. But neither are recommended for production systems.
The class files within your patch jar should now be used rather than your original class files since the class loader will pick what it finds first. When you are done with your testing, you can simply remove the patch jar and restart again. You can even leave the configuration in place – a missing patch jar shouldn’t cause any trouble.
Tags: class loader, classpath, jar, Java, patch