Influencing class loading at runtime Add comment to Wiki View in Wiki Edit Wiki page Printable Version

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.

 

Search

Results of your search request can come from various sources: the Groovy website itself, the JIRA issues, the API documentation, as well as a few other interesting Groovy-related blogs.

  By  -  pages  -  views  - last modified