gpt4 book ai didi

groovy - 检查是否直接执行 Groovy 脚本

转载 作者:行者123 更新时间:2023-12-01 14:11:44 24 4
gpt4 key购买 nike

在 Python 中,可以检查 if a script is being invoked directly通过检查是否 __name__ == '__init__'

Groovy 中是否有与此等效的东西?

最佳答案

我想最简单的方法是将当前类名(使用 class.simpleName)与实际执行的文件脚本名进行比较这是一个例子:

让我们在 M.groovy 文件中创建第一个类:

class M {
static main(args){
def m = new M()
}
def M(){
def thisClass = this.getClass().simpleName
def callingClass = new File(getClass().protectionDomain.codeSource.location.path).name.with{ it.take(it.lastIndexOf('.')) }
println("thisClass: ${thisClass}, callingClass: ${callingClass}")
if (thisClass == callingClass){
println 'Calling from M class...'
} else {
println 'Calling from outside.'
}
}
}

现在来自外部类,例如T.groovy 你可以调用实例化 M 类:new M()。当你执行 M.groovy 你得到:

thisClass: M, callingClass: M
Calling from M class...

当您运行 groovy T.groovy 时,您将获得:

thisClass: M, callingClass: T
Calling from outside.

希望这对您有所帮助。

关于groovy - 检查是否直接执行 Groovy 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52543035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com