0

Currently I have a small Groovy Script that I'm using in multiple places. I want to be able to include it in other Groovy scripts by using grapes. I may want to use this library in a Java project in the future.

Is it possible to compile and 'install' this script (e.g using maven or gradle) and keep it in Groovy?

Mfswiggs
  • 307
  • 1
  • 6
  • 16

1 Answers1

0

Installing the Groovy Library

I was able to get this working by doing the following:

First create a gradle project using the following build.gradle:

apply plugin: 'groovy'
apply plugin: 'maven'

group = "local"
version = "0.1.0"

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.5'
}

install {
    repositories.mavenInstaller {
        pom.artifactId = "math"
    }
}

I created my class in src/main/groovy/local/math/Arithmetic.groovy:

package local.math

public class Arithmetic
{
    public static int add (int x, int y) {
        return x + y
    }
}

Then to install the library run gradle install.

For Groovy

In a separate script I have:

@Grab(group="local", module="math", version="0.1.0")
@GrabExclude("org.codehaus.groovy:groovy-all")
import local.math.Arithmetic

println Arithmetic.add(3, 8)

For Java

I created a new Gradle project with the following build.gradle:

apply plugin: 'application'

mainClassName = "local.math.Test"

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies {
    compile ('local:math:0.1.0')
}

Then I created the following in `src/main/java/local/math/Test.java:

package local.math;

import local.math.Arithmetic;

public class Test
{
    public static void main(String[] args) {
        System.out.println(Arithmetic.add(1,5));
    }
}

And finally it runs with gradle run.

Mfswiggs
  • 307
  • 1
  • 6
  • 16