Search code examples
javajar.class-file

Compare .java file to .class file


In my situation I have many .jar files being created from a build process. Before I do any debugging I want a way to quickly verify that my .java source matches the .class found in a .jar.

I figure that if I unzip the .jar and find the .class which matches my .java file then I should be able to determine if they're functionally the same.

How can I do this?


Solution

  • The first thing to realize is that compilation doesn't just use the specific .java file for the class being compiled. The compiler also uses information from the other .java and .class files available at compile time. For example, it may inline static final constants. Also, stuff like method overloading depends on which methods have been defined.

    That being said, if you compile the same source file with the same compiler as before, you'll probably get the same, or a very similar class file. However, even with identical source files, different compilers (javac vs eclipse) and different versions of the compiler will produce different results.

    Therefore, what I'd recommend is first try compiling everything and see if the classfiles match. If the class files don't match, try disassembling them with the Krakatau disassembler and do a diff on the diassemblies to see what the differences are. That will help you see if the difference is unimportant (such as a reordering of the constant pool) or if there are substantive changes to the bytecode.