3
//bytecode of <init>
0:    aload_0
1:    invokespecial java.lang.Object.<init> ()V (8)
4:    return
//bytecode of <main>
0:    getstatic     java.lang.System.out Ljava/io/PrintStream; (16)
3:    ldc       "Hello World" (22)
5:    invokevirtual java.io.PrintStream.println (Ljava/lang/String;)V (24)
8:    return

The above is the byte code for :

public class Hi {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}

If I have only the byte code, how do I run it? Can I? And what's the extention of the byte code file? Hi.class?

4
  • 8
    That's definitely not the byte code for that class. That byte code is just for the default constructor. Commented Sep 6, 2012 at 10:36
  • 1
    Do you mean that you have a textual representation of the bytecode and you want to compile it in .class file? Commented Sep 6, 2012 at 10:37
  • I'm sorry...will edit the question now... Commented Sep 6, 2012 at 10:47
  • Yes Matteo. I have the textual representation of the bytecode and i want to compile it and run it. Commented Sep 6, 2012 at 10:50

1 Answer 1

1

You can compile byte code using Jasmin which has its own format. You need the byte code for the entire class, not just the body of a method.

Once you have the byte code you can load it in a custom class loader or call defineClass on the current class loader and run it.

You may find that compiling and running from the source is easier with the use of the Compiler API or BeanShell.

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you Peter.I took each method at a time and generated the byte code. I'm assuming that is the wrong way to generate the bytecode. Is yes can you help me out with the right way?
The byte code is binary, you appear to be dumping a text representation of the byte code which is for you understanding only and is not designed to be "compiled" What tool are you using to "generate the byte code"?
First you told "I have only the byte code", now you say you take method at a time and generate bytecode for it. Where from do you take methods? from a .class file?
Good point, using javap requires you have the byte code already (which can be run) from which you generate readable, but not runnable text
One can get runnable text from bytecode with java decompiler, or, if java decompiling fails, using jasmine decompiler.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.