Last active
December 21, 2023 03:21
-
-
Save skrb/927c146e6d9f33d528ff5fcc8d358f0a to your computer and use it in GitHub Desktop.
Compiler APIサンプル その1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.util.List; | |
import javax.tools.JavaCompiler; | |
import javax.tools.JavaFileObject; | |
import javax.tools.StandardJavaFileManager; | |
import javax.tools.ToolProvider; | |
public class CompilerTest { | |
public static void main(String... args) throws IOException { | |
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); | |
if (compiler == null) { | |
System.err.println("No Compiler"); | |
return; | |
} | |
// 仮想ファイルマネージャの取得 | |
// 第1引数 コンパイルエラー処理コールバック | |
// 第2引数 ロケール nullだとデフォルトロケール | |
// 第3引数 文字セット nullだとデフォルト文字セット | |
try (StandardJavaFileManager fileManager | |
= compiler.getStandardFileManager(null, null, null)) { | |
// 抽象ソースファイルの取得 | |
Iterable<? extends JavaFileObject> files = fileManager.getJavaFileObjects("Hello.java"); | |
// コンパイルタスクの生成 | |
// 第1引数 コンパイラメッセージの出力 nullの場合System.errが使われる | |
// 第2引数 仮想ファイルマネージャー | |
// 第3引数 コンパイルエラーのコールバック 指定しない場合はnull | |
// 第4引数 コンパイラオプション 指定しない場合はnull | |
// 第5引数 アノテーションプロセッサ 指定しない場合はnull | |
// 第6引数 ソースファイル群 | |
JavaCompiler.CompilationTask task = compiler.getTask( | |
null, fileManager, null, | |
List.of("--enable-preview", "--release", "22"), | |
null, files); | |
// コンパイル | |
// 成功すればtrueが戻る | |
var result = task.call(); | |
System.out.println(result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment