You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java调用JRuby时,如何从StackTraceElement获取脚本名称?

JRuby中获取脚本名称的方法

我在使用JRuby时,经常从其他脚本中调用脚本,这导致从Java调用方获取StackTrace时,并非所有StackTraceElement都来自初始调用类。

例如,这段Ruby代码:

public
  def compute()
    return 10
  end

对应的StackTraceElement信息如下:

  • declaringClass: RUBY
  • methodName: compute
  • fileName: <script>
  • lineNumber: 3

我希望获取该脚本的名称,请问在JRuby中是否可行?我当前通过以下方式创建脚本:

RubyRuntimeAdapter adapter = JavaEmbedUtils.newRuntimeAdapter();
IRubyObject io = adapter.eval(runtime, <scriptContent>);

解决方案

可行,可通过以下几种方式实现:

  1. eval时指定脚本名称
    使用RubyRuntimeAdapter的重载eval方法,传入自定义的脚本名称参数:
// 替换为你的目标脚本名称,比如"my_business_script.rb"
String scriptName = "custom_script.rb";
IRubyObject io = adapter.eval(runtime, scriptContent, scriptName);

设置后,生成的StackTraceElement中fileName字段会显示你指定的脚本名称,而非默认的<script>。

  1. Ruby代码内部获取脚本名
    如果需要在Ruby逻辑中直接获取当前脚本名称,可使用Ruby内置的__FILE__常量:
public
  def compute()
    puts "当前脚本名称: #{__FILE__}"
    return 10
  end

配合上面指定名称的eval方法执行时,__FILE__会返回你设置的脚本名称。

  1. Java侧解析JRuby调用栈
    如果已经生成了异常栈,可通过JRuby的RubyException API获取Ruby层面的完整调用栈,其中会包含脚本名称:
try {
    // 执行你的脚本逻辑
} catch (RubyException e) {
    List<String> backtrace = e.getBacktrace();
    for (String line : backtrace) {
        // 每行格式示例:"custom_script.rb:3:in `compute'"
        System.out.println(line);
    }
}

内容的提问来源于stack exchange,提问作者Hervé Girod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:45:59