Dynamic Java Compilation

In some Unit Test project, we had a need for a dynamic code generation, naturally followed by a compilation.

The goal was to assemble several Unit Tests into a single Test Suite.
The natural path is to write a Test Suite class, compile it, and run it. The problem happens when you want to automate this kind of process...

There is in Java 1.6 a class named javax.tools.JavaCompiler, that can help.
The steps are the following ones:

  1. Generate the java code, in a String (StringBuffer, byte array, CharSequence, what not)
  2. Compile the code - into a class
  3. Load the compiled code with the ClassLoader so it is available in the classpath
  4. Run the generated class

The default behavior of the JavaCompiler is to write the compiled class on the disc, and this is not what we wanted, as the directory you run your code from might very well be a read-only directory.
There is actually a way to keep the compiled class in memory, as illustrated by the attached file.

There is some frustrating restriction though. The JavaCompiler cannot be used with a custom ClassLoader. This means that a class generated by a dynamic compilation as described above cannot be used for any further dynamic compilation.
For example, you generate
ClassA. Then you generate ClassB, extending ClassA, generated and loaded. The compilation of ClassB throws a ClassNotFoundException about ClassA...
That is something to keep in mind. If this issue remains, a workaround would be to generate JVM byte code, using libraries like ASM; it works very well, but this makes the code a bit more difficult to debug, and beside, Java and JVM byte code are two (very) different languages.


Comments:

good

Posted by guest on August 22, 2011 at 01:56 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About


This is the blog for the Oracle FMW Architects team fondly known as the A-Team. The A-Team is the central, technical, outbound team as part of the FMW Development organization working with Oracle's largest and most important customers. We support Oracle Sales, Consulting and Support when deep technical and architectural help is needed from Oracle Development.
Primarily this blog is tailored for SOA issues (BPEL, OSB, BPM, Adapters, CEP, B2B, JCAP)that are encountered by our team. Expect real solutions to customer problems, encountered during customer engagements.
We will highlight best practices, workarounds, architectural discussions, and discuss topics that are relevant in the SOA technical space today.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today