Thursday, October 3, 2013

Grails Groovy dynamically invokeMethod with empty/single/multi parameters

You need to first get bean object of your service class.
Create a service like below and get your required service by calling:


serviceFinderService.getServiceByName("serviceName");

 If you have a service named "StudentService.groovy" then replace "serviceName" with "Student" or "student".


package com.pritom.services

import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes

class ServiceFinderService {
    private static HashMap beanList = new HashMap();
    private def grailsApplication;
    private static def ctx;

    def serviceMethod() {

    }

    public def getServiceByName(String bean) throws Exception {
        if(!ctx) {
            ctx = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
        }
        bean += "Service";
        bean = bean[0].toLowerCase() + bean.substring(1);
        if(beanList.containsKey(bean)) {
            return beanList.get(bean);
        }
        beanList.put(bean, ctx.getBean(bean));
        if(beanList.containsKey(bean)) {
            return beanList.get(bean);
        }
        throw new Exception("Invalid service");
    }
}


Now check and invoke the method if a specific method existing by such way:


def studentService = ServiceFinderService.getServiceByName("Student");

if(studentService.metaClass.respondsTo(studentService, "methodName", [Integer, String, Boolean] as Object[]) {
    def result = studentService.invokeMethod("methodName", [1, "Pritom K Mondal", true] as Object[]);
}

/* If your method is static then call it by: */
if(studentService.metaClass.respondsTo(studentService, "methodName", [Integer, String, Boolean] as Object[]) {
    def result = studentService.metaClass.getTheClass().invokeMethod("methodName", [1, "Pritom K Mondal", true] as Object[]);
}


No comments:

Post a Comment