Programming in Java bytecode

≡放荡痞女 提交于 2019-11-27 05:14:31

问题


I'm looking to write a short program (maybe a Hello World) in Java bytecode. I just want to write the bytecode using my text editor and run it. How would I do this? Got an example? Thanks!


回答1:


You could try Jasmin!

.class public HelloWorld
.super java/lang/Object

.method public static main([Ljava/lang/String;)V
  .limit stack 3
  .limit locals 1

  getstatic      java/lang/System/out Ljava/io/PrintStream;
  ldc            "Hello World."
  invokevirtual  java/io/PrintStream/println(Ljava/lang/String;)V

  return

.end method

You compile it using:

> java -jar jasmin.jar hello.j

And then you run it like any class:

> java HelloWorld
Hello World.

Update

I see that your question mentions "without using Javac or Java". Could you clarify how you meant that statement?




回答2:


I've created a new Java bytecode assembler that is backwards compatible with Jasmin but also adds lots of new features and simplifies the syntax slightly.

Here's an example of how you might write a Hello World program.

.class public hello
.super java/lang/Object

.method public static main : ([Ljava/lang/String;)V
    .limit stack 10
    .limit locals 10

    getstatic java/lang/System out Ljava/io/PrintStream;
    ldc "Hello World!"
    invokevirtual java/io/PrintStream println (Ljava/lang/Object;)V
    return
.end method

I've also written a tutorial on bytecode assembly. It currently only covers Hello, World, but I can continue it if there is interest.




回答3:


Maybe this article can get you started: Bytecode basics (a little old, but you will get the idea).

The class file format will come in handy too :D




回答4:


Byte code is written as actual bytes, which are not normally easily editable by a normal text editor.

This means you will need something that converts a textual representation to binary. A reasonable place to start would be an assembler like Jasmin.




回答5:


Have you considered JBE (Java Bytecode Editor) ?
It's based on Apache's Bytecode Engineering Library (BCEL)




回答6:


This guy here guides you through the process of writing a class file of a hello world program step by step. Pretty exciting stuff :-) https://medium.com/@davethomas_9528/writing-hello-world-in-java-byte-code-34f75428e0ad



来源:https://stackoverflow.com/questions/3150254/programming-in-java-bytecode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!