程式扎記: [ 常見問題 ] How do I include jars in a groovy script?

標籤

2016年9月29日 星期四

[ 常見問題 ] How do I include jars in a groovy script?

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:
  1. this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())  
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
  1. #!/usr/bin/env groovy  
  2. import java.io.File  
  3.   
  4. printf("\t[Info] Loading Test.jar...\n")  
  5. this.class.classLoader.rootLoader.addURL(new File("Test.jar").toURL())  
  6.   
  7. printf("\t[Info] Initializing Test object...\n")  
  8. testObj = Class.forName("demo.Test").newInstance()  
  9.   
  10. printf("\t[Info] Invoke API on Test object...\n")  
  11. testObj.hello("John")  
Execution example:
$ ./test.groovy
[Info] Loading Test.jar...
[Info] Initializing Test object...
[Info] Invoke API on Test object...
Hello John


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!