Los objetos Groovy extienden las capacidades de los objetos Java. El intérprete Groovy maneja de forma diferente las llamadas a métodos para objetos Groovy y para objetos Java.
Existen tres tipos de objetos:
Los objetos Groovy son definidos en la clase Java GroovyObject
dentro del paquete
groovy.lang
. Véase el correspondiente fuente Java:
lhp@nereida:~/src/groovy/groovyinterpreter/groovy-1.7.2/src/main/groovy/lang$ sed -ne '/^package/,$p' GroovyObject.java | cat -n 1 package groovy.lang; 2 3 /** 4 * The interface implemented by all Groovy objects. 5 * <p/> 6 * Especially handy for using Groovy objects when in the Java world. 7 * 8 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> 9 * @version $Revision: 9880 $ 10 */ 11 public interface GroovyObject { 12 13 /** 14 * Invokes the given method. 15 * 16 * @param name the name of the method to call 17 * @param args the arguments to use for the method call 18 * @return the result of invoking the method 19 */ 20 Object invokeMethod(String name, Object args); 21 22 /** 23 * Retrieves a property value. 24 * 25 * @param propertyName the name of the property of interest 26 * @return the given property 27 */ 28 Object getProperty(String propertyName); 29 30 /** 31 * Sets the given property to the new value. 32 * 33 * @param propertyName the name of the property of interest 34 * @param newValue the new value for the property 35 */ 36 void setProperty(String propertyName, Object newValue); 37 38 /** 39 * Returns the metaclass for a given class. 40 * 41 * @return the metaClass of this instance 42 */ 43 MetaClass getMetaClass(); 44 45 /** 46 * Allows the MetaClass to be replaced with a derived implementation. 47 * 48 * @param metaClass the new metaclass 49 */ 50 void setMetaClass(MetaClass metaClass); 51 }
Existe la correspondiente clase GroovyObject que permite el acceso a estos métodos y atributos desde Groovy.
Los métodos invokeMethod
, getProperty
,
setProperty
pueden ser utilizados para crear dinámicamente atributos y métodos.
Los métodos getMetaClass
y setMetaClass
facilitan la intercepción e inyección de métodos en POGOs.
Una clase en la JVM es un metaobjeto. Una clase
cargada en la JVM no puede ser modificada. Sin embargo si que es posible modificar su MetaClass
asociada llamando al método
MetaClass()
.
Casiano Rodríguez León