Self modifying code in Java [closed]

余生长醉 提交于 2019-11-28 09:16:32

Ignoring the world of grief you could be causing yourself via self-modifying code(!), it seems to me there are 3 options:

  1. use the inbuilt compiler support of Java 6 and write/recompile/reload classes
  2. use the Apache BCEL bytecode manipulation library to write your class directly
  3. make use of Java 6's inbuilt scripting support (or use Apache BSF) to write methods in your JVM scripting language of choice, and execute these

Of the three above, my initial choice (in the absence of requirements) would be to take a look at option 3. I suspect it's the least painful way to start. I've used all of the above - unfortunately I can't post links to client code.

You can write (Java) code that generates new classes (byte code) at runtime using a library like bcel. That's not quite the same as self-modifying code. I suspect self-modifying code is not something the JVM supports.

For an example of generating new code at runtime, have a look at the source code of clojure.

That should be difficult to realize. But you can create at runtime new classes and load them with a custom classloader. If you want to modify the code again, you have to reload the class.

From BCEL:

The Byte Code Engineering Library is intended to give users a convenient possibility to analyze, create, and manipulate (binary) Java class files (those ending with .class). Classes are represented by objects which contain all the symbolic information of the given class: methods, fields and byte code instructions, in particular.

I see these options for this purpose:

  • Generate the java source code and compile it with the external javac or the internal compiler tools (can't remember the name). And as you are responsible for the naming, just include a version count in the class name to avoid class loading anomalies.
  • Use the built in JavaScript engine support
  • Some scenarios can be solved using java Proxys

Edit: I once created a Java 1.4 program which took business rules from an existing legacy database, generated java files (basically implementations of a Predicate interface) with a bunch of println() from them and used the command line javac to compile them.

As an undergrad I got to work on the JikesRVM. It is a JVM implemented (mostly) in Java. At runtime it will JIT compile itself! It's a really cool piece of technology.

You could always just use a dynamic language...

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