我猜最简单的方法是将当前类名(使用 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.