Skip to end of metadata
Go to start of metadata

When writing a script, it may be unwieldy to call the script defining the whole classpath at the command line, e.g.

groovy -cp %JAXB_HOME%\bin\activation.jar;%JAXB_HOME%\bin\... myscript.groovy

You can go the other way - let the script itself find the jars it needs and add them to the classpath before using them. To do this, you need to

1. get the groovy rootloader

def loader = this.class.classLoader.rootLoader

2. introduce the necessary uls to groovy rootloader. Use whatever logic suits your situations to find the jars / class directories

3. Load the classes you need:

4. To instantiate the classes, use the newInstance method:

Note that newInstance is on steroids when called from groovy. In addition to being able to call the parameterless constructor (as w/ Java's Class.newInstance()), you can give any parameters to invoke any constructor, e.g.

You can also pass a map to initialize properties, e.g.

The downside of using this approach is that you can't inherit from the classes you load this way - classes inherited from need to be known before the script starts to run.

  • No labels

2 Comments

  1. What about loading classes defined in groovy scripts?

  2. Seems to me that this would hold some promise for getting around the problem of TemplateServlet not recognizing 'import' statements in Groovlet code.

    Could you possibly show how that could be done?

    My groovy fu is a bit weak.

    When I try the code you gave, the script ends (with no error message of any kind) at the very first line,

    def loader = this.class.classLoader.rootLoader
    

    oddly, the entire code works just fine when I run the same script at the command line.

    Thanks...