Say you have a Groovy code like
As explained in Groovy Backstage, there is bytecode generated to achieve the desired behaviour of printing to stdout.
The easiest way of looking at the generated bytecode is to groovyc your Groovy source to a class file and process it with a Java Decompiler (e.g. JAD). See also: From source code to bytecode
The resulting code looks as follows (only the relevant snippet):
There is a delegation scheme like
ScriptBytecodeAdapter.invokeMethod(...) (static method)
InvokerHelper.invokeMethod(...) (static method)
Invoker.invokeMethod(...) (instance method called on InvokerHelper's single instance)Invoker calls invokeMethod(...) on the MetaClass of our class (with exceptions, see below). It finds this MetaClass by looking it up in the MetaClassRegistry. The Invoker holds a single instance of this registry.
When working with the MetaClassRegistry, |
Exceptions (when MetaClass.invokeMethod(...) is not used):
Closure.invoke(...) is usedGroovyInterceptable, obj.invokeMethod(methodName,asArray(arguments)) is calledGroovyObject obj when method invokation through its MetaClass fails, obj.invokeMethod(methodName,asArray(arguments)) is calledMetaClass.invokeMethod(...) finally cares for the invokation, either by reflection or by dynamic bytecode generation. Dynamic bytecode generation is supposed to be faster. For a class MyClass it generates gjdk.groovy.lang.MyClass_GroovyReflector with an invoke method.
Does MyClass_GroovyReflector contain methods according to MyClass.groovy that can be called directly ![]()
The cool thing about MetaClass is that you can dynamically add or remove methods to it. One can even replace the whole MetaClass in the MetaClassRegistry. See ProxyMetaClass for an example.
back to Groovy Backstage