0

I am trying to dynamically compile java classes in runtime. The java files gets generated in System.getProperty("java.io.tmpdir") folder. When it is done generated the java files get compiled being used it gets deleted. My method of dynamically compilation is grabbed from this question

How do you dynamically compile and load external java classes?

Now in my test classes they successfully get generated, compiled and loaded but when I do a mvn:clean install and maven runs through the tests then suddenly the packages used in the generated classes can not be found. One of the tests I wrote, calls the method and then generates these classes, it is kind of lazy loading where only when the generated classes is needed by other code it gets generated.

/tmp/java/CH3.java:3: error: 
package foo.bar does not exist
import foo.bar.Generated;


/tmp/java/CH3.java:17: error: 
cannot find symbol
Generated generated
^

I assume it has something to do with the ClassLoader or JavaFileManager not containing the packages it needs for the java file to get compiled.

Also this error occurs the moment the compiler tries to compile the java file.

Do you have any idea how to fix this problem ?

Community
  • 1
  • 1
Sand Man
  • 75
  • 1
  • 11
  • Why are you generating classes in `java.io.tmpdir`? Generate them under `target` since you have a Maven project, and add them to the buildpath with the [`build-helper-maven-plugin`](http://www.mojohaus.org/build-helper-maven-plugin/usage.html). – Tunaki Nov 22 '16 at 15:17
  • OK I will give your answer a shot – Sand Man Nov 23 '16 at 06:15
  • I am guessing the classes need to be already generated when I run the mvn:clean install command. If so the solution won't work. The generated classes does not exist at the point. When a test runs, in one of the tests the generate method gets called. – Sand Man Nov 23 '16 at 06:33
  • Not necessarily, the build generates sources in the `generate-sources` phase, and add them to the buildpath, so that they are present in it when compiling. – Tunaki Nov 23 '16 at 08:15
  • so how do I specify what to generate ? As at the moment I pass a string builder which a file writer writes the string to a java file. Takes the file and compiles it directly afterwards. – Sand Man Nov 23 '16 at 08:19
  • I thought you were generating _sources_, not compiling on the fly. Please edit your question with all of the information and describe exactly what you want to achieve. Perhaps having a separate project generating a JAR and having a dependency on it is the better approach. – Tunaki Nov 23 '16 at 08:21

0 Answers0