I wanted to dynamically load a class at runtime and run a function specified in the argument in groovy.

Example 

./run.sh Utilities.uptime

To get that to work,

  1. Read in the argument from the command prompt
  2. String classFunctionName = args[0]
    logger.trace("classFunctionName - " + classFunctionName)
    
  3. Split the name of class and function
  4. //Split the name of class and function
    String[] split=classFunctionName.split("\.")
    String className = split[0]
    logger.trace("className - " + className)
    
    //Name of function
    String action = split[1]
    logger.trace("action - " + action)
    
  5. Dynamically looked up the function
  6. //Dynamically load class
    Utilities.environment = Class.forName(environmentName)
    logger.trace(Utilities.environment.toString())
    
    def classAction = Class.forName(className)
    logger.trace(classAction.toString())
    
  7. Finally invoked it
  8. logger.trace("About to run " + classAction + "." + action + "()")
    
    classAction."${action}"()
    
    logger.trace("Completed " + classAction + "." + action + "()")
  9. If an argument had to provided Example
     ./run.sh test "ABC D"

    the code was modified very slightly

  10. //If arguments are passed - Example  ./run.sh test "ABC D"
    if (args.size() > 1) {
    	String arguments = args[1]
    
    	logger.trace("About to run " + classAction + "." + action + "(" + arguments + ")")
    
    	//Dynamically call function
    	classAction."${action}"(arguments)
    
    	logger.trace("Completed " + classAction + "." + action + "(" + arguments + ")")
    }
    
Tagged with:
 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close