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


沒有留言:

張貼留言

[Linux 常見問題] sudo: Sorry, you must have a tty to run sudo Error on a Linux and Unix

Source From  Here   Preface   I‘m trying to run the following command:  #   ssh  user@box.example.com  sudo command1 /path/to/file But, a...