Disassemble Java class files via javap
Today I received the question how someone could see the Java code for a Java class file. You can disassemble the Java byte code via the command line tool javap.
Lets assume you have this tiny Java class Test.java
package test;
public class Test {
int number = 5;
public void sayHello() {
System.out.println("Hello");
}
}
Compile this class via javac Test. javaand you receive Java.class
If you you run javap Test you receive the attributes and method signatures.
C:\temp\javaptest>javap Test
Compiled from "Test.java"
public class test.Test extends java.lang.Object{
int number;
public test.Test();
public void sayHello();
}
If you you run javap -C Test you receive the byte-code
C:\temp\javaptest>javap -c Test
Compiled from "Test.java"
public class test.Test extends java.lang.Object{
int number;
public test.Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: aload_0
5: iconst_5
6: putfield #2; //Field number:I
9: return
public void sayHello();
Code:
0: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #4; //String Hello
5: invokevirtual #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}
To get the full Java source code you can use the tool jad.
16.11.2008 Updated entry based on comments from Eric and Phil. Thanks!
November 16th, 2009 at 9:30 pm
javap is a disassembler, not a decompiler. jad is a decompiler.
November 16th, 2009 at 10:17 pm
I also recommend using JAD in case you want to decompile class files. It also features an Eclipse plugin but I never used that.
Notice that javap merely prints attributes and method signatures, no values and method bodies.
November 17th, 2009 at 1:06 am
@Eric @Phil: Thank you for your comments. I updated the blog entry based on your input.
December 15th, 2009 at 4:47 pm
Jad is an excellent decompiler but it’s not maintained for ages (the latest version is 1.5.8g). To workaround some Jad limitations (mostly for Java 1.4 and 1.5+ classes), there exists a tool called JadRetro which prepares the class files before running Jad.
An alternative solution is JD-GUI decompiler which understands Java generics but, IMHO, it can’t compete with Jad at present (at least, in generating compilable code).