7

In my code I open my file.java and parse him with JavaParser.

FileInputStream in = new FileInputStream(".../file.java");

        CompilationUnit cu;

        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }

........

file.java:

public class File{

     public void ownMethod(){...}

     public static void main(String[] args){

          ownMethod(5); //Note the extra parameter

     }
}

In file.java there is an error: The method main calls the method ownMethod with one parameter, but ownMethod expects 0 parameters. JavaParser doesn't detect this error and parses file.java with this error. How can I know (in my code) whether file.java has no errors? Is it posible without using a java compiler?

3
  • class needs to be written using a lowercase c. :) Commented Dec 7, 2014 at 18:18
  • No problem, its those small things you never see yourself. :) Commented Dec 7, 2014 at 18:25
  • This is possible with the Eclipse JDT eclipse.org/jdt . Of course, this is a Java Compiler in some sense, but it can be deployed as a bunch of JARs. Commented Dec 8, 2014 at 9:21

1 Answer 1

5

Is it posible without using java compiler?

No. Any solution, which your (re?)invent, will lead you to yet-another-one compiler. Parse & validate for errors is an essential part of compiler's job.

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

3 Comments

Well IDE can verify that without explicitly compiling it (yes, it actually DOES compile it, but in background and you never see it, so that counts I guess)
@MightyPork Explicitly or implicitly, it does compile it. So ursa's point stands.
I agree: there are many things for which you basically need a compiler. However we are planning to build some validation in JavaParser itself in the future, so we can check if the AST is valid. For a full validation we would also need to use JavaSymbolSolver, which resolve types and method calls. It basically re-implement a lot of stuff you find in a compiler.

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.