Have you ever created or encountered a self modifying code in Java? If yes, then please post the link or simply post the code.
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.
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.
Ignoring the world of grief you could be causing yourself via self-modifying code(!), it seems to me there are 3 options:
- use the inbuilt compiler support of Java 6 and write/recompile/reload classes
- use the Apache BCEL bytecode manipulation library to write your class directly
- 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.