我可以创建一个Groovy项目的JAR并在Java项目中使用Groovy类

时间:2015-11-04 08:23:10

标签: java groovy

目前我有一个我在多个地方使用的小型Groovy脚本。我希望能够通过使用葡萄将其包含在其他Groovy脚本中。我可能希望将来在Java项目中使用此库。

是否可以编译和“安装”此脚本(例如使用maven或gradle)并将其保存在Groovy中?

1 个答案:

答案 0 :(得分:0)

安装Groovy Library

我能够通过以下方式实现这一目标:

首先使用以下build.gradle创建一个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"
    }
}

我在src/main/groovy/local/math/Arithmetic.groovy创建了我的课程:

package local.math

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

然后安装库运行gradle install

对于Groovy

在另一个脚本中我有:

@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

我使用以下build.gradle创建了一个新的Gradle项目:

apply plugin: 'application'

mainClassName = "local.math.Test"

repositories {
    mavenCentral()
    mavenLocal()
}

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

然后我在`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));
    }
}

最后它与gradle run一起运行。

相关问题