1

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)?
4
  • 3
    You could always try to compile the code... Commented Sep 13, 2010 at 7:55
  • 4
    What's wrong with using javac for the first 2 bullet points? Commented Sep 13, 2010 at 7:55
  • umm.. nothing is wrong with it. I never taught of compiling java code from java. I'll do some googling on it. thanks. Commented Sep 13, 2010 at 8:09
  • You have to google about the compiler? Commented Sep 13, 2010 at 8:15

2 Answers 2

3

Java 6 introduced the Compiler API. This can be used to to compile Java code without calling an external compiler. Here's a short introduction.

Sign up to request clarification or add additional context in comments.

Comments

2
  • 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.