如何获取 Scala 中当前的脚本或类名?
我希望我的 Scala 程序能够以编程方式确定其脚本文件名或其类名,将字符串存储在变量 program
中并打印出名称。
Java 有几种 方法来实现此目的。
I'd like my Scala program to be able to programmatically determine either its script filename or its class name, store the string in a variable program
and print out the name.
Java has several methods for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为这是最简单的:
I think this is the simplest:
按照 0__ 提示解析堆栈跟踪应该可以处理大多数用例,特别是当具有 main 方法的对象不在同名文件中时:
然后您可以这样调用:
或者您混合到您的main object
这适用于脚本 scala A.script,无论代码是否包装在对象中。当使用 scalac 编译并作为 scala A 运行时,这也适用。当使用 REPL 运行时,将返回
。Parsing the stack trace as hinted by 0__ should take care of most of the use cases, in particular when the object with the main method is not in a file of the same name:
Then you call this like that:
or you mix in into your main object
This works for scripts
scala A.script
whether the code is wrapped in an object or not. This also works when compiled withscalac
and run asscala A
. When run with the REPL, this will return<none>
.不太确定你在寻找什么......
给了我
并
给了我
Not exactly sure what you are looking for...
gives me
And
gives me
Rosetta 代码
Rosetta Code