2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaParser でソースファイルのコメントを削除

Posted at

できるだけ java ソースファイルのサイズを小さくしたいと思い、ソースファイルのコメントを全部削除したらいいんじゃないと思ったら
意外と難しい。

普通の正規表現で置換はうまくいかないパターンもあるから、やはりjava の parser が必要じゃないかと探したら、ありました。

でも、最新版だと、「Javadoc を出力しない」、「コメントを出力しない」と設定してもうまくできなかった。
ちょっと古い版(3.12.0)は問題なくできました。

要は、java ソースを分析して、Javadoc や コメントを除いて出力する。

pom.xml
<!-- https://mvnrepository.com/artifact/com.github.javaparser/javaparser-core -->
<dependency>
    <groupId>com.github.javaparser</groupId>
    <artifactId>javaparser-core</artifactId>
    <version>3.12.0</version>
</dependency>
App.java
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.printer.PrettyPrinterConfiguration;
import com.github.javaparser.printer.PrettyPrinterConfiguration.IndentType;

public class App {
    public static void main(String[] args) throws IOException {
        Path source = Paths.get("AbstractWebSocket.java");

        JavaParser.getStaticConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_8);
        CompilationUnit unit = JavaParser.parse(source);
        PrettyPrinterConfiguration conf = new PrettyPrinterConfiguration();
        //conf.setIndentType(IndentType.SPACES);
        conf.setIndentType(IndentType.TABS);
        conf.setIndentSize(1); // tab 1個はスペースより省エネ
        //conf.setTabWidth(1);
        conf.setPrintComments(false); // コメントを出力しない
        conf.setPrintJavadoc(false); // Javadoc を出力しない
        conf.setEndOfLineCharacter("\n"); // 改行1byte
        System.out.println(unit.toString(conf));
    }
}

参考になった記事
https://qiita.com/opengl-8080/items/50ddee7d635c7baee0ab
https://javaparser.org/setting-java-8-9-10-etc/

以上!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?