Sunday, June 13, 2010

Dynamic Java compilation, from a String

Kind of out the the scope of this blog, but as it made me sweat, it might be interesting for some people... The main goal was initially to be able to dynamically override a method of some (Java) class, compile and run it.
I used it for Unit Testing (JUnit), to have the setUp() method of some generic test object to initialize some System variables, context dependent (defined by some properties file).
It's about being able to dynamically generate the code to compile into a String (or StringBuffer, or byte array, or whatever...), compile, load and run it. It is not as trivial as it sounds.
Here is the code I used.

And it is possible not to write the class on the file system. Everything happens in memory.

No comments: