如何简单地在另一个groovy脚本中导入一个groovy文件 [英] how to simply import a groovy file in another groovy script
问题描述
〜/ groovy
%tree
。
├──lib
│├──GTemplate.class
│└──GTemplate.groovy
└──Simple.groovy
class GTemplate {
static def toHtml(){
this.newInstance()。toHtml1()
}
def toHtml1(){
test$
import lib。*
class简单扩展GTemplate {
}
错误:
$ b
% groovyc Simple.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException:
启动失败:编译不完整:希望找到类
lib.GTemplate在/ home / bhaarat / groovy / lib / GTemplate.groovy,但
文件包含类:GTemplate 1错误
解决方案看起来你正在将Groovy与类似PHP的技术混为一谈。
因为更接近Java,如果一个子类存在于子文件夹中,它需要exis t在一个同名的包中。在你的例子中,你可以将这一行添加到
GTemplate.groovy
的顶部并重新编译文件:
package lib
然而,这意味着完全限定名称现在GTemplate实际上是
lib.GTemplate
。这可能不是你想要的。
另外,如果你想在不使用包的情况下使用子文件夹中的文件,你可以删除
import 语句来自
Simple.groovy
,而是像这样编译和运行类:groovyc -classpath $ CLASSPATH:./ lib / Simple.groovy
groovy -classpath $ CLASSPATH:./ lib / Simple
注意:如果您没有
CLASSPATH
已经设置,您可以简单地使用:groovyc -classpath ./lib/ Simple.groovy
groovy -classpath ./lib/简单
另外,对于Windows机器,将
至
%CLASSPATH%;
我强烈建议学习有关软件包并了解其工作原理的知识。查看这篇维基百科关于Java包的文章作为起点。
~/groovy % tree . ├── lib │ ├── GTemplate.class │ └── GTemplate.groovy └── Simple.groovy class GTemplate { static def toHtml() { this.newInstance().toHtml1() } def toHtml1() { "test" } } import lib.* class Simple extends GTemplate { }
Error:
% groovyc Simple.groovy org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Compilation incomplete: expected to find the class lib.GTemplate in /home/bhaarat/groovy/lib/GTemplate.groovy, but the file contains the classes: GTemplate 1 error
解决方案It looks like you are confusing Groovy with PHP-like techniques.
Because it's closer to Java, if a class exists within a subfolder, it needs to exist within a package of the same name. In your example, you could add this line to the top of
GTemplate.groovy
and recompile the file:package lib
However, this means that the fully-qualified name for GTemplate is now actually
lib.GTemplate
. This may not be what you want.Alternatively, if you want to use the files from a subfolder without using packages, you could remove the
import
statement fromSimple.groovy
, and instead compile and run the class like so:groovyc -classpath $CLASSPATH:./lib/ Simple.groovy groovy -classpath $CLASSPATH:./lib/ Simple
NOTE: If you don't have a
CLASSPATH
already set, you can simply use:groovyc -classpath ./lib/ Simple.groovy groovy -classpath ./lib/ Simple
Also, for windows machines, change
$CLASSPATH:
to%CLASSPATH%;
I strongly recommend learning about packages and understanding how they work. Look at this Wikipedia article on Java packages for a starting point.
这篇关于如何简单地在另一个groovy脚本中导入一个groovy文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!