簡體   English   中英

無法使Groovy擴展模塊正常工作

[英]Unable to get Groovy extension module to work

我正在嘗試創建擴展模塊,然后在其他項目/腳本中使用它,但無法使其正常工作。 這是我在做什么:

步驟1:創建一個名為TemperatureUtils.groovy的文件,它是一個類類別的類。 來源如下:

package utils

class TemperatureUtils {

    Double toFahrenheit(Number celcius) {
        (9 * celcius / 5) + 32
    }

    Double toCelcius(Number fahrenheit) {
        (fahrenheit - 32) * 5 / 9
    }
}

步驟2:創建擴展模塊描述符org.codehaus.groovy.runtime.ExtensionModule,其內容如下:

moduleName=Some-Utils
moduleVersion=1.0
extensionClasses=utils.TemperatureUtils
staticExtensionClasses=

步驟3:編譯該類並手動創建一個具有以下結構的jar文件:

extensionUtils.jar
  |-- utils
  |     |-- TemperatureUtils.class
  |
  |-- META-INF
        |-- services
              |-- org.codehaus.groovy.runtime.ExtensionModule

步驟4:創建一個新腳本以使用擴展模塊。 腳本來源:

import org.codehaus.groovy.control.CompilerConfiguration

def groovyScript = '''
//Following line just confirms that the jar file is indeed on the classpath of this script
assert 25 == (new utils.TemperatureUtils()).toCelcius(77)

//Actually using the category now
assert 77.toCelcius()       == 25
assert 25.toFahrenheit()    == 77
'''

def compilerConfig = new CompilerConfiguration()

compilerConfig.setClasspath(/E:\temp\jar\extensionUtils.jar/)

def shell = new GroovyShell(compilerConfig)
shell.evaluate(groovyScript)

步驟5:執行腳本。 在這里,我得到以下異常:

groovy.lang.MissingMethodException: No signature of method: java.lang.Integer.toCelcius() is applicable for argument types: () values: []
    at Script1.run(Script1.groovy:6)
    at ConsoleScript2.run(ConsoleScript2:16)

現在,我已經嘗試了一些方法,但是無法正常工作:

  • 從擴展模塊描述符中刪除了最后一行-“ staticExtensionClasses =”,但沒有用。
  • 通過使用@Category(Number)批注並從這兩種方法中刪除參數(並在方法的主體中使用“ this”代替“ celcius”和“ fahrenheit”參數名),將TemperatureUtils.groovy類更改為實際類別。但是它仍然沒有用。
  • 用谷歌搜索,但沒有找到太多信息。 也偶然發現了這一點 ,但這也無濟於事。

非常感謝出色的stackoverflow社區可以提供的任何幫助! :)

以下對我有效,使用Groovy 2.4.5。 基於這篇文章

首先,將TemperatureUtils更改為具有static方法:

包工具

class TemperatureUtils {
    static Double toFahrenheit(Number celcius) {
        (9 * celcius / 5) + 32
    }

    static Double toCelcius(Number fahrenheit) {
        (fahrenheit - 32) * 5 / 9
    }
}

然后,我將不使用CompilerConfiguration而只是設置CLASSPATH 例如

$ export CLASSPATH=../utils/build/libs/temp.jar
$ groovy client.groovy

其中Client.groovy只是:

def groovyScript = '''
//Following line just confirms that the jar file is indeed on the classpath of this script
assert 25 == (new utils.TemperatureUtils()).toCelcius(77)

//Actually using the category now
assert 77.toCelcius()       == 25
assert 25.toFahrenheit()    == 77
'''

def shell = new GroovyShell() 
shell.evaluate(groovyScript)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM