Search code examples
javadesign-patternscode-generationcompilation

How to validate generated Java code's syntax?


I made a little app to generate Java test classes based on certain set of information. Basically, I am generating the boilerplate code needed for a library that we are using.

I would like to test the generated code in better way than just comparing the output to an expected string.

  • Is there any facility to test if the Java code contains errors?
  • Is there any facility to determine if the Java file will compile?
  • Is there a strategy that I should use for this kind of situation (I was thinking of using Class class to get information about the class)?

Solution

    • Is there any facility to test if the Java code contains errors?

    • Is there any facility to determine if the Java file will compile?

    • Is there a strategy that I should use for this kind of situation?

    Yes - compile the file with the Java compiler.

    Note that you can call the Java compiler at runtime, either by using Runtime.exec(...) or the the JavaCompiler API. The latter approach is described in:

    and there are lots of other resources on the subject.

    However, your primary goal seems to be to check that your generators are generating correct Java code; e.g. as part of your application tests. For that, it would be simplest to off-load the problem to a shell script that uses javac to the compile the code with an appropriate classpath, checks the compiler's return code, and greps the compiler output for error and warning messages.

    But ... as you are probably aware ... simply compiling the generated code doesn't guarantee that it will be correct.


    I was thinking of using Class class to get information about the class.

    That won't help. The Class class is only relevant for classes that have been successfully compiled and successfully loaded by the JVM. And even then it doesn't tell you if there were syntax (or other) errors in the original code.