简体   繁体   English

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

[英]Can I create a JAR of a Groovy project and use the Groovy classes within a Java project

Currently I have a small Groovy Script that I'm using in multiple places. 目前,我有一个小的Groovy脚本,正在多个地方使用。 I want to be able to include it in other Groovy scripts by using grapes. 我希望能够通过使用葡萄将其包含在其他Groovy脚本中。 I may want to use this library in a Java project in the future. 将来我可能想在Java项目中使用此库。

Is it possible to compile and 'install' this script (eg using maven or gradle) and keep it in Groovy? 是否可以编译和“安装”此脚本(例如,使用Maven或Gradle)并将其保存在Groovy中?

Installing the Groovy Library 安装Groovy库

I was able to get this working by doing the following: 通过执行以下操作,我可以使此工作正常进行:

First create a gradle project using the following build.gradle : 首先使用以下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"
    }
}

I created my class in src/main/groovy/local/math/Arithmetic.groovy : 我在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 . 然后要安装库,请运行gradle install

For Groovy 对于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 对于Java

I created a new Gradle project with the following build.gradle : 我使用以下build.gradle创建了一个新的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: 然后我在`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 . 最后,它与gradle run一起gradle run

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM