Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 236
user1951618 Avatar asked Dec 07 '14 18:12

user1951618


1 Answers

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.

like image 76
ursa Avatar answered Sep 18 '22 12:09

ursa