You can invoke the Eclipse compiler yourself from command line in the same way you use javac
: you need the ECJ
jar. For example, you can compile a class with:
java -jar ecj-4.2.2.jar hello.java
This can be easily automated if you need, there are some tips on using ECJ and especially for compiling programmatically and ant compiling on this page.
You can use the compiler from the eclipse packages, or get it directly separated from the Eclipse downloads. At the time of this writing, the current latest release is 4.3 and the ECJ compiler can be found on the Eclipse 4.3.0 download page. Look for the JDT Core Batch Compiler
package.
From the comments of the other answer, it seems that you need to display the compiled bytecodes, you can invoke javap
after the compilation:
javap -c -p -s -v hello
Edit : show compiled class
I was wondering if / how to get a class dump in the same way Eclipse can show it. There is no way as easy as for invoking the eclipse compiler, but I have found a mean anyway by reusing Eclipse internal classes together with a minimal class wrapper.
ClassDump.java
import java.io.RandomAccessFile;
import java.io.FileInputStream;
import java.io.DataInputStream;
import org.eclipse.jdt.internal.core.util.Disassembler;
import org.eclipse.jdt.core.util.ClassFormatException;
/**
* ClassDump : show a classfile dump the same way as Eclipse
*/
class ClassDump {
public static void main(String[] args){
System.out.println("Class dumper");
if(args.length != 1){
System.out.println("Usage : Disasm <file.class>");
System.exit(1);
}
new ClassDump(args[0]);
}
public ClassDump(String classfile){
byte[] classbuf = readClassBytes(classfile);
System.out.println(String.format("Class size = %d bytes", classbuf.length));
Disassembler dis = new Disassembler();
try {
System.out.print(dis.disassemble(classbuf, "\n", org.eclipse.jdt.internal.core.util.Disassembler.DETAILED));
} catch(ClassFormatException cfe){
cfe.printStackTrace();
}
}
private byte[] readClassBytes(String classfile){
byte[] buf;
try{
RandomAccessFile raf = new RandomAccessFile(classfile,"r");
FileInputStream fis = new FileInputStream(raf.getFD());
DataInputStream dis = new DataInputStream(fis);
buf = new byte[(int)raf.length()];
dis.readFully(buf);
dis.close();
fis.close();
raf.close();
} catch (Exception ex){
ex.printStackTrace();
return new byte[0];
}
return buf;
}
}
On my local host, I compile with (you will probably need to change the jar name):
javac -cp \dev\tools\eclipse\plugins\org.eclipse.jdt.core_3.8.3.v20130121-145325.jar ClassDump.java
And the run has a bunch of dependencies with the Eclipse runtime jars (JDT core, osgi, equinox, ...), so I am cheating by using a wildcard to let java get all the needed jars:
java -cp .;\dev\tools\eclipse\plugins\* ClassDump SomeClass.class
It will print the same output as Eclipse clas file editor... HTH!