Seb
Seb

Reputation: 1851

Test if java-code does NOT compile

It might sound a little bit weird, but I am looking for a possibility to test if some statements in the code are rejected by the typechecker (which means that the code should NOT compile).

Be explain my intend: I am running a controlled experiment on type-systems where my subjects have to write some methods in java for me. The functionality of the methods written by the subjects can be easily tested using unit-tests, but I also want the methods to be well-typed (which means that some methodcalls should not be allowed).

One way I could imagine to achieve that would be writing the statements which should break the build into a seperate file, add it to the classpath and run javac to see if any error occurs during the build. Although this might work, it does not feel very sophisticated, so my question is: Is there any better way to (automatically) test if some statements are refected by the typechecker?

Upvotes: 3

Views: 1205

Answers (2)

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

Have you looked at the Checker Framework? It can be used to static code analysis and more. It might be a good fit for what's you are doing. Here is the link on my answer with an example of the annotation type processor.

Also you may find the Java Compiler API quite helpful. It allows to execute javac programmatically in a single java machine. So you could use it as a part of your tests.

Upvotes: 4

CDahn
CDahn

Reputation: 1876

This is a variation of the Halting Problem, which isn't solvable in the general case. To do this, you have to run (or in this case compile) the code. Therefore, the solution you've already proposed is the best solution.

Upvotes: 5

Related Questions