- 適用於 JDK 23 的 GraalVM(最新)
- 適用於 JDK 24 的 GraalVM(搶先體驗)
- 適用於 JDK 21 的 GraalVM
- 適用於 JDK 17 的 GraalVM
- 封存
- 開發建置
將 Insight 嵌入應用程式
將 Insight 嵌入 Java #
Graal 語言 (使用 Truffle 框架實作的語言,例如 JavaScript、Python、Ruby 和 R) 可以透過 Polyglot Context API 嵌入到自訂 Java 應用程式中。GraalVM Insight 也可以透過相同的 API 來控制。像
final Engine engine = context.getEngine();
Instrument instrument = engine.getInstruments().get("insight");
Function<Source, AutoCloseable> access = instrument.lookup(Function.class);
AutoCloseable handle = access.apply(agentSrc);
取得 Context
的 Engine
,並請求 insight
instrumentation。
然後使用 GraalVM Insight 腳本建立 `Source`,並在取得其 instrumentation 控制代碼時套用它。當不再需要時,使用 `handle.close()` 停用所有腳本的 instrumentation。例如:```java Source instrument = Source.create("js", """ insight.on('return', function(ctx, frame) { console.log(`Instrumented where = ${frame.where}`); }, { roots: true, rootNameFilter: 'end', }); """); Source script = Source.create("js", """ function end() { var where = 'end'; console.log(where + ' invoked') } end(); """); try (Context context = Context.newBuilder().build()) { @SuppressWarnings("unchecked") Function<Source, AutoCloseable> insight = context.getEngine().getInstruments().get("insight").lookup(Function.class); // 在沒有 instrumentation 的情況下執行 context.eval(script); // 在有 instrumentation 的情況下執行 try (AutoCloseable handle = insight.apply(instrument)) { context.eval(script); } // 在沒有 instrumentation 的情況下執行 context.eval(script); } ``` 請參閱 [嵌入依賴項設定](/latest/reference-manual/embed-languages/#dependency-setup)。新增 `insight` 的依賴項:```