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 = ???
3
  • 1
    please write some algorithm, i am unable to get what you are talking about. Commented Sep 14, 2011 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... Commented Sep 14, 2011 at 11:44
  • Try to use systemcall to write a file and run 'javac'. Process proc = Runtime.getRuntime().exec("javac MyClass.java"); Commented Sep 14, 2011 at 11:45

4 Answers 4

6

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

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

Comments

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.

Comments

0

There is a compiler API.

Example can be seen here:

Comments

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.