Skip to content

Instantly share code, notes, and snippets.

@skrb
Last active December 21, 2023 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skrb/36055887b0ac032df2dc224b386d34ec to your computer and use it in GitHub Desktop.
Save skrb/36055887b0ac032df2dc224b386d34ec to your computer and use it in GitHub Desktop.
Compiler API その2 文字列をソースにする
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 CompilerTest2 {
private static String HELLOCLASS = """
public class Hello {
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}
""";
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
= List.of(new StringJavaFileObject("Hello", HELLOCLASS));
// コンパイルタスクの生成
// 第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);
}
}
}
import java.net.URI;
import javax.tools.SimpleJavaFileObject;
public class StringJavaFileObject extends SimpleJavaFileObject {
private String content;
public StringJavaFileObject(String className, String content) {
super(URI.create("string:///"
+ className.replace('.', '/')
+ Kind.SOURCE.extension),
Kind.SOURCE);
this.content = content;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment