In - statically compiled - Java, static code that invokes instance code will not compile. This is because of the high risk that static code is not called by the instance, but called by type, directly - which will lead to runtime errors.
While it is theoretically possible to compile Groovy code statically, the default is to compile it dynamically. “Dynamically” means that, in part, there are no direct links between code artifacts (such as methods, variables, constructors, classes, etc.) in the bytecode.
Consider the following Groovy class:
class StaticClass { static def someString = "someString" static def staticMethod() { this.someString } static def main(args) { StaticClass.staticMethod() new StaticClass().staticMethod() } }
Using the Groovy compiler, groovyc , it is compiled into code that provides dynamic execution at runtime. The following code represents the above main(..) method after compilation:
public static void main(String[] args) { CallSite[] arrayOfCallSite = $getCallSiteArray(); arrayOfCallSite[0].call($get$$class$StaticClass()); arrayOfCallSite[1].call(arrayOfCallSite[2].callConstructor( $get$$class$StaticClass())); return; }
What really happens when this code is called is hard to say, because at runtime there is a very complex and nested flow of decisions and a workflow that depends on several factors.
As in this simple example, there are no special cases (metaclass, expandometaclass, closures, interceptors, etc.), it is likely that, after all, the implementation of GroovyObject.invokeMethod(String, Object) .
Throughout the Groovy documentation (including the User Guide and Wiki, but until the missing JavaDocs and missing source files in the source distribution), the mechanics of this “dynamic metaprogram runtime” are hidden from the user - perhaps because of this, it’s a huge complication and because the user doesn’t You need to know about this in detail. This is quite interesting for the main Groovy developers.
So, in the end, it's hard to say why this works when the object instance is not called. Another question: should it work ...