如何在Scala中获取当前脚本或类名? [英] How do I get the current script or class name in Scala?
本文介绍了如何在Scala中获取当前脚本或类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的Scala程序能够以编程方式确定其脚本文件名或其类名,将该字符串存储在变量程序
中并打印出名称。
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有几种方法this。
Java has several methods for this.
推荐答案
// With help from huynhjl
// http://stackoverflow.com/questions/8129185#8131613
import scala.util.matching.Regex.MatchIterator
object ScriptName {
val program = {
val filenames = new RuntimeException("").getStackTrace.map { t => t.getFileName }
val scala = filenames.indexOf("NativeMethodAccessorImpl.java")
if (scala == -1)
"<console>"
else
filenames(scala - 1)
}
def main(args: Array[String]) {
val prog = program
println("Program: " + prog)
}
}
a href =http://rosettacode.org/wiki/Program_name#Scala =nofollow> Rosetta代码
Rosetta Code
这篇关于如何在Scala中获取当前脚本或类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文