- 面向 JDK 23 的 GraalVM(最新版本)
- 面向 JDK 24 的 GraalVM(抢先体验)
- 面向 JDK 21 的 GraalVM
- 面向 JDK 17 的 GraalVM
- 存档
- 开发版
将洞察力嵌入应用程序
将洞察嵌入 Java #
Graal 语言(使用 Truffle 框架实现的语言,例如 JavaScript、Python、Ruby 和 R)可以通过 多语言上下文 API 嵌入到自定义 Java 应用程序中。GraalVM 洞察也可以通过相同的 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` 仪器。
然后使用 GraalVM 洞察脚本创建 `Source`,并在获取其仪器句柄时应用它。使用 `handle.close()` 在不再需要时禁用所有脚本的仪器。例如:```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); // 在没有仪器的情况下运行 context.eval(script); // 使用仪器运行 try (AutoCloseable handle = insight.apply(instrument)) { context.eval(script); } // 在没有仪器的情况下运行 context.eval(script); } ``` 查看 [嵌入依赖关系设置](/latest/reference-manual/embed-languages/#dependency-setup)。添加对 `insight` 的依赖关系:```