Search code examples
javaparsingjavaparser

JavaParser doesn't remove comments before package declaration


I am writing a Java application that removes comments from Java files.

I wrote this code:

static void removeComments(Node node) {
        for (Comment child : node.getAllContainedComments()) {
            child.remove();
        }
    }

CompilationUnit cu = JavaParser.parse(projectDir); // projectDir is received from parameter
removeComments(cu);

It kind of works. However, if there are block comments before the package declarations, the code won't remove those comments.

For example, this code:

/*
 * Block comment
 */
// Line comment
package test;

/*
 * Block comment
 */
// comment
/**
 *
 * @author Me
 */
public class Test {

    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("print 1"); // comment in code line
        // comment 2
        System.out.println("print 2");
        /*
        block comment
         */
    }

}

Becomes this code:

/*
 * Block comment
 */
package test;

public class Test {

    public static void main(String[] args) {
        System.out.println("print 1");
        System.out.println("print 2");
    }
}

Is it a bug from JavaParser, or am I missing something?

Edit:

If I put a line comment at the beginning of the file, the first block comment (the one before the package declaration) will be removed, but not this line comment. I think JavaParser doesn't consider that the first line of a file may be a comment.


Solution

  • I'm the maintainer of JavaParser.

    1. Please open an issue on GitHub for this
    2. The easiest way to remove all comments is to configure JavaParser not to handle comments at all:

      import com.github.javaparser.ast.CompilationUnit;
      
      public class RemoveComments {
          public static void main(String[] args) {
              JavaParser.getStaticConfiguration().setAttributeComments(false);
              CompilationUnit cu = JavaParser.parse("/**a*/package a.b.c; //\nclass X{}");
              System.out.println(cu);
          }
      }