Decompile and change Java classes without source

Christian Müller
30. March 2015
Reading time: 2 min

Often it is necessary to look in Java classes to understand bugs or misbehaviour. But not always a source code of this library or class exists. With eclipse and a plugin it is no longer a problem to manage this. The Java Decompiler allows you to decompile class files, bare or within a jar, to a suitable source code. Now you can easily debug your program or software with the generated source and explore its behaviour.

But if you found a program that has shows misbehaviour in the code, you can copy the source and reimplement (or fix) it and use your own recompiled software. When this class is a member of a Java archive, you could take a few steps to recompile a fixed new one:

At first create a Java project in eclipse, and import your program as project library. Then you have to find the “defect” class and copy its decompiled code to a new Java class with same name. Let the quick fixes move it to the right directory and fix imports. Often imports are only interfaces of the program but the implementing class is required. A rough understanding of the code is necessary for resolving the right dependencies. When finished fixing imports, and the misbehaviour let eclipse compile your code. Now you have a new class file in the target directory of your project. With the following command you can replace the archived class with a new, reimplemented one: 

$ jar -fu your-program.jar com/your/program/package/java.class

The path to the class in this command must be the same as the old class lies in the archive. That means e.g. for a war file, the path has to begin with WEB-INF/classes/ .

Now your program is “fixed” and hopefully has the right behaviour.