无法使Groovy扩展模块工作
我试图创建一个扩展模块,然后在另一个项目/脚本中使用它,但无法使其工作。以下是我正在做的: 步骤1:创建一个名为TemperatureUtils.groovy的文件,它是一个类类。资料来源如下:无法使Groovy扩展模块工作,groovy,extension-methods,groovyshell,groovy-console,extension-modules,Groovy,Extension Methods,Groovyshell,Groovy Console,Extension Modules,我试图创建一个扩展模块,然后在另一个项目/脚本中使用它,但无法使其工作。以下是我正在做的: 步骤1:创建一个名为TemperatureUtils.groovy的文件,它是一个类类。资料来源如下: package utils class TemperatureUtils { Double toFahrenheit(Number celcius) { (9 * celcius / 5) + 32 } Double toCelcius(Number fah
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
方法:
包utils
class TemperatureUtils {
static Double toFahrenheit(Number celcius) {
(9 * celcius / 5) + 32
}
static Double toCelcius(Number fahrenheit) {
(fahrenheit - 32) * 5 / 9
}
}
然后,我不会使用编译器配置
,而是简单地设置类路径
。例如
$ 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)