4

I want to conduct a little experiment, and generate a java program in a String (the experiment is itself in Java).

Now I want to test whether it compiles or not. How do I take a String object in Java and see whether it is legal Java code?

Clarification:

String prog = "public interface B {public void speak();}"
boolean doesItCompile = ???
Amir Rachum
  • 76,817
  • 74
  • 166
  • 248
  • 1
    please write some algorithm, i am unable to get what you are talking about. – amod Sep 14 '11 at 11:43
  • 1
    First thing that comes to mind (since it's fairly obvious): write strings to a .java file. And then try to compile it using `Runtime.exec`. And then read the standard output and error streams. But there might be an easier way... – mre Sep 14 '11 at 11:44
  • Try to use systemcall to write a file and run 'javac'. Process proc = Runtime.getRuntime().exec("javac MyClass.java"); – tgmath Sep 14 '11 at 11:45

4 Answers4

6

You should look into javax.tools.JavaCompiler. see this article.

MByD
  • 135,866
  • 28
  • 264
  • 277
1

Take a look at JavaCompiler. The API documentation provides an example of how to create a number of compilation tasks and invoke call on each one. The call method returns a boolean to indicate whether each compilation attempt was successful.

Adamski
  • 54,009
  • 15
  • 113
  • 152
0

There is a compiler API.

Example can be seen here:

ZenMaster
  • 12,363
  • 5
  • 36
  • 59
0

If you just want to verify if the content of the String is legal Java code then you should have a look at antlr. It can be used to parse a java source file and create an abstract syntax tree. If that fails, then the input is not valid.

The first answer to this question shows a working example with a simple grammar. You'd have to use the Java grammar instead.

Community
  • 1
  • 1
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268