10

Do anyone have an idea whats the best way of creating an own library for groovy.

I have several methods which i just dont want copy and paste into all my groovy scripts.

The perfect solution would be to do it by an

import myownmethods

How to create the library myownmethods.jar?

Thanks for any answer and solution

Cheers

Booyeoo
  • 585
  • 5
  • 8
  • 21

2 Answers2

14

The simplest method is to compile your groovy files with groovyc and then package them into a jar file with jar. For example:

groovyc -d classes myclasses.groovy
jar cvf myclasses.jar -C classes .

I'd also consider looking at gradle. To get started, you can use a build.gradle containing just:

apply plugin: 'groovy'

Then put your source files in a subdirectory called src/main/groovy and run gradle jar. It will build your source files into a jar file in build/libs.

ataylor
  • 64,891
  • 24
  • 161
  • 189
  • Thanks for the fast answers! I tried it with the groovyc method, and i got my jar file in the end. I copied it into the lib dir of groovy main dir, but when i open the groovyConsole and type following:`import myclasses.* one() // method which just do println 1` it doesnt seem to work... he cant find the method. What have i done wrong? – Booyeoo Nov 20 '11 at 11:19
  • Stick the jar file in `.groovy/lib` in your home directory (`System.properties['user.home']`). Or launch groovy with `groovyConsole -classpath myclasses.jar` – ataylor Nov 20 '11 at 18:11
  • Thanks a lot! I copied into all possible folders but it didnt work. I then realized that you might need a class definition in the groovy which is compiled to class and packed into the jar. Works. This is not perfect but gives the needed workaround. – Booyeoo Nov 20 '11 at 23:26
2

You should follow the same process that you would for a Java library, i.e.

  • Create a project for the code
  • Configure your favorite build tool (Ant, Maven, etc.) to build a JAR for that project
  • Put the JAR somewhere where other projects can find it. If you're using a tool like Ivy or Maven that does dependency management you'll likely want to deploy it to a repository. Otherwise, you can probably just put it somewhere in source control †
  • Projects that depend on this library should either load it from the repository (if using dependency management), or have it copied into their lib directory (if not) †

† I know this sucks, but I can't remember how I used to manage dependencies without using a dependency management tool

Dónal
  • 185,044
  • 174
  • 569
  • 824