Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile to java bytecode (without using Java)

Tags:

My compilers class is creating a language that we intend to compile to Java Bytecode. We have made plenty of progress and are nearing the time where it's time for code generation.

We are having problems locating information on how to create .class files from our compiler. Do you have any resources that can give us some assistance? We already have plenty of documentation on the instruction set, but need information on how to directly fill out the class file/the writing of hex.

We do not need information or suggestions on decompiling the .class files.

Even a simple example of writing out a .class file from scratch would be excellent.

The JVM spec is not what we're after. What we really need is an example or a walkthrough.

like image 878
Allyn Avatar asked Mar 27 '09 00:03

Allyn


People also ask

Can we compile a Java program without JVM?

You can't run Java program without JVM. JVM is responsible in running a Java program, but the only file that can be executed by JVM is Java bytecode, a compiled Java source code.

Can C be compiled to Java bytecode?

Axiomatic Solutions has an answer to this problem called Axiomatic Multi-Platform C (AMPC). This software can compile C source files directly into Java class files.

What compiles Java code into bytecode?

Java source code is compiled into bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file extension .

Is bytecode only in Java?

Bytecode runs only when the interpreter is available. It runs on the Java virtual machine only. It gives flexibility by giving a quote 'Write code once, run code anywhere'. It also saves a lot of time for a programmer.


1 Answers

There are a number of projects out there that provide a high level interface to creating Java class files without you having to write the class files yourself. Take a look at the following:

  • ASM - http://asm.objectweb.org/
  • BCEL - http://jakarta.apache.org/bcel/
  • Trove - http://teatrove.sourceforge.net/trove.html

All provide an API to create class files. You could always look at the code they've written to do this and write some similar code for your compiler although I would imagine that it's a fair amount of work.

With BCEL take a look at ClassGen, that should enable you to write out class files in the format you want, a simple example follows:

ClassGen cg = new ClassGen("HelloWorld", "java.lang.Object",
                             "<generated>", ACC_PUBLIC | ACC_SUPER,
                             null);
like image 182
Jon Avatar answered Sep 20 '22 15:09

Jon