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?

Pokechu22
  • 4,984
  • 9
  • 37
  • 62
user1951618
  • 131
  • 12

1 Answers1

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.

ursa
  • 4,404
  • 1
  • 24
  • 38
  • 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 Dec 07 '14 at 19:05
  • 1
    @MightyPork Explicitly or implicitly, it does compile it. So ursa's point stands. – lexicore Dec 07 '14 at 19:14
  • 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. – Federico Tomassetti Nov 28 '16 at 12:30