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


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...