美文网首页程序员
Directly Modifying Java Class Fi

Directly Modifying Java Class Fi

作者: Jelif | 来源:发表于2018-06-17 19:21 被阅读6次

    Suppose that there is a class file Main.class which prints Hello World! when we run java Main in our command line:

    $ java Main
    Hello World!
    

    What if we want to let it print Hello China! rather than Hello World! ? Like this:

    $ java Main
    Hello China!
    

    Traditionally, we can make it by:

    1. decompile the class file to a java file
    2. modify that java file
    3. compile the java file to a new class file

    But it’s inefficient. After all, what we want is to get a class file who can print Hello China!, why bother java file?

    At least for this question, the best choice is to modify the class file directly, and hopefully, there are many binary editors can help us to do so. For myself, I prefer using vim to handle the problem:

    1. using vim -b to open Main.class in binary mode
    2. replace World with China
    3. save and quit

    After that, let’s rerun the java Main command:

    $ java Main
    Hello China!
    

    The reason this can be done is that JVM only knows class file, in other words, JVM doesn’t care whether the class file is compiled by a compiler or has been modified after that.

    Finally, the source of Main.class is too simple to proudly list here:

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

    相关文章

      网友评论

        本文标题:Directly Modifying Java Class Fi

        本文链接:https://www.haomeiwen.com/subject/gjoweftx.html