Source From Here
Question
I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using #!/usr/bin/env groovy at the top of my script.
How-To
If you really have to load a JAR at runtime with:
For example, consider a jar "
Test.jar" which contains class demo.Test with API:hello(String name), then you can call it this way:
- test.groovy
Execution example:
Question
I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using #!/usr/bin/env groovy at the top of my script.
How-To
If you really have to load a JAR at runtime with:
- this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())
- test.groovy
- #!/usr/bin/env groovy
- import java.io.File
- printf("\t[Info] Loading Test.jar...\n")
- this.class.classLoader.rootLoader.addURL(new File("Test.jar").toURL())
- printf("\t[Info] Initializing Test object...\n")
- testObj = Class.forName("demo.Test").newInstance()
- printf("\t[Info] Invoke API on Test object...\n")
- testObj.hello("John")
沒有留言:
張貼留言