In Python, one can check if a script is being invoked directly by checking if __name__ == '__init__'
.
Is there any equivalent to this in Groovy?
In Python, one can check if a script is being invoked directly by checking if __name__ == '__init__'
.
Is there any equivalent to this in Groovy?
I guess the easy way is to compare the current class name (using class.simpleName
) to the actual executing file script name
here is an example:
let's create the first class in M.groovy
file:
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.'
}
}
}
Now from external class e.g. T.groovy
you can call an instantiate M
class: new M()
.
when you execute M.groovy
you got:
thisClass: M, callingClass: M
Calling from M class...
and when you run groovy T.groovy
you'll get:
thisClass: M, callingClass: T
Calling from outside.
Hope this helps.