Showing posts with label GroovyObject. Show all posts
Showing posts with label GroovyObject. Show all posts

Saturday, August 5, 2017

Grails Groovy: Execute Code transparent before and after any method is invoked | Override Method Implementation | Override Method Body

Grails Groovy: Execute Code transparent before and after any method is invoked | Override Method Implementation | Override Method Body.
Note:-
  • Make sure the returned value from the method call is returned from the closure as well
  • Might be a expensive of a class has number of methods with heavy implementation
  • If selective execution is required, then check for the method name and then intercept the call


class Dummy {
    def method1() { 
        System.out.println "In method 1"
    }

    def method2(String str) { 
        System.out.println "In method 2"
    }
    
    static def method3(int a, int b) {
        System.out.println "In static method 3" 
    }    
}

Dummy.metaClass.invokeMethod = {String name, List args ->
   def result = null

   System.out.println("Do something before $name is called with args $args")

   try {
       result = delegate.metaClass.getMetaMethod(name, args).invoke(delegate, args)
   }
   catch(Exception e) {
        System.out.println "Handling exception for method $name"
   }

   System.out.println("Do something after $name was called with args $args")

   return result
}

Dummy.metaClass.'static'.invokeMethod = {String name, List args ->
   def result = null

   System.out.println("Do something before static method $name is called with args $args")

   try {
       result = delegate.metaClass.getMetaMethod(name, args).invoke(delegate, args)
   }
   catch(Exception e) {
        System.out.println "Handling exception for method $name"
   }

   System.out.println("Do something after static method $name was called with args $args")

   return result
}

def dummy = new Dummy()
dummy.method1()
dummy.method2('Test')
Dummy.method3(1, 2)