La mayor diferencia de este código con el anterior es que la
casle SimplePOGO
no implementa GroovyInterceptable
y no dispone de un método invokeMethod()
.
generaciondecodigos@nereida:~/Lgroovy/objects$ cat -n AOP2.groovy 1 class SimplePOGO { 2 void simpleMethod1(){ 3 System.out.println("simpleMethod1() called") 4 } 5 6 void simpleMethod2(String param1, Integer param2){ 7 System.out.println("simpleMethod2(${param1},${param2}) called") 8 System.out.println("sleeping...") 9 Timer.sleep(2000) 10 } 11 12 } 13 14 SimplePOGO.metaClass.invokeMethod = { String name, args -> 15 System.out.println("time before ${name} called: ${new Date()}") 16 17 //Get the method that was originally called. 18 def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args) 19 20 calledMethod?.invoke(delegate, args) 21 22 System.out.println("time after ${name} called: ${new Date()}\n") 23 } 24 25 simplePogo = new SimplePOGO() 26 simplePogo.simpleMethod1() 27 simplePogo.simpleMethod2("stringParam", 24) 28 simplePogo.simpleMethod3(1, 2, 4)En la llamada
calledMethod?.invoke(delegate, args)
debemos referirnos a delegate
ya que this
hace alusión
al objeto clausura. Dentro de la clausura delegate
se refiere
al objeto cuyos métodos estan siendo interceptados.
generaciondecodigos@nereida:~/Lgroovy/objects$ groovy AOP2.groovy time before simpleMethod1 called: Tue Feb 23 16:47:40 WET 2010 simpleMethod1() called time after simpleMethod1 called: Tue Feb 23 16:47:40 WET 2010 time before simpleMethod2 called: Tue Feb 23 16:47:40 WET 2010 simpleMethod2(stringParam,24) called sleeping... time after simpleMethod2 called: Tue Feb 23 16:47:42 WET 2010 time before simpleMethod3 called: Tue Feb 23 16:47:42 WET 2010 time after simpleMethod3 called: Tue Feb 23 16:47:42 WET 2010