Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monkeypatch a .class file in a jar

I have a jar file that cannot be modified, but I want to use a different .class file in place of one of the members of the jar. How can I tell Java to use the external .class file when the code within the jar attempts to load it?

like image 870
Ignacio Vazquez-Abrams Avatar asked Nov 01 '22 14:11

Ignacio Vazquez-Abrams


1 Answers

You could compile another jar file with replacement classes with exactly the same name and put it ahead of the jar file in the class path. For example, this is what the various slf4j bridge jars do to replace calls to log4j or Jakarta Commons Logging in library code with cognate slf4j code; one need not maintain two sets of logging systems and configurations that way.

If you want to override a java... class, you can use some of the command line options to change the boot class path. Look at the -Xbootclasspath options in http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html. Heed the warnings.

There is also the lib/endorsed directory if you need to upgrade a third-party jar that Sun uses. Oracle uses other organizations' XML and CORBA libraries; if they release a new version and you need to adopt it, you can.

You can use AspectJ to instrument the code and possibly replace it. An around advice can call the original code if it wants.

You could see if you really need to replace the original code. Some systems provide customization hooks.

like image 138
Eric Jablow Avatar answered Nov 09 '22 10:11

Eric Jablow