I have some interesting exercise - to read .java file with Java, to find every code part in this .java file(like methods and etc.) and to say how many line numbers we have in every method without whitespaces and comments and also to find the count of items in every method.
Here is some example that I use - so could Java Parser. With the code I can say how many line numbers I have in method, but cannot remove the count of whitespaces and comments. Can someone help me?
The code:
public static void main(String[] args) throws ParseException, IOException {
File f = new File(".").getAbsoluteFile();
File srcRoot = new File(f, "src");
String srcFilename = TestMethodLineNumber.class.getName().replaceAll("\\.", "/") + ".java";
File src = new File(srcRoot, srcFilename);
System.out.println(f);
System.out.println(srcRoot);
System.out.println(src);
getMethodLineNumbers(src);
}
private static void getMethodLineNumbers(File src) throws ParseException, IOException {
CompilationUnit cu = JavaParser.parse(src);
new MethodVisitor().visit(cu, null);
}
/**
* Simple visitor implementation for visiting MethodDeclaration nodes.
*/
private static class MethodVisitor extends VoidVisitorAdapter {
@Override
public void visit(MethodDeclaration m, Object arg) {
System.out.println("From [" + m.getBeginLine() + "," + m.getBeginColumn() + "] to [" + m.getEndLine() + ","
+ m.getEndColumn() + "] is method:");
System.out.println(m);
}
}
}