How to check if a Java source file is valid (has no errors)?

2k views Asked by At

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?

1

There are 1 answers

3
ursa On BEST ANSWER

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.