Groovy:为什么在同一个包中的类需要导入? [英] Groovy: Why is Import required for classes in the same package?
问题描述
一个包中的简单Groovy类 com.something
package com.something
class A {
}
同一个包中的另一个类
package com.something
class B {
def variable = new A()/ /不工作,直到我明确地说import com.something.A
}
为什么B类无法访问类A,即使它们都在同一个包中?解析方案
可悲的是,问题确实如此没有真正需要的信息来完全回答它。但我可以告诉以下几点。如果你在那里建立一个目录./com/something/并将A.groovy和B.groovy写出来,然后使用命令行 groovyc ./com/something/A.groovy ./com/something进行编译/B.groovy
,那么这个必须工作。到目前为止,该目录并不重要,但如果您更改为 groovyc ./com/something/B.groovy
,则目录会发生变化,因为现在groovyc必须发现A. groovy并且需要正确的目录结构。
现在,groovyc的ant,gradle和maven版本通常如何工作,是提供一个完整的源代码列表。如果没有这样做,编译可能会失败。但是,如果A和B的根目录不同,并且你不给这两个编译器,那么它肯定会失败。
我不知道这是否是原因,所以我希望将这个答案更多地理解为指向可能错误的指针。希望这有助于
A simple Groovy Class in a package com.something
package com.something
class A {
}
Another class in the same package
package com.something
class B {
def variable=new A() //DOES NOT WORK TILL I EXPLICITLY say "import com.something.A"
}
Why Class B is not able to access class A, even though they both are in the same package?
Sadly the question does not really have the needed information to answer it completely. But I can tell the following. If you make a directory ./com/something/ and out A.groovy and B.groovy in there and then compile them using the commandline groovyc ./com/something/A.groovy ./com/something/B.groovy
, then this must work. So far the directory is not really important, but that changes if you change to groovyc ./com/something/B.groovy
, because now groovyc has to "discover" A.groovy and requires the correct directory structure for this.
Now, how the ant, gradle and maven version of groovyc normally work is by supplying a complete list of sources. If this is not done, compilation may fail. But if the root directories for A and B are different and you do not give both to the compiler, then it will surely fail.
I cannot know if that is the reason, so I want this answer more understood as a pointer to what might be wrong. Hope this helps
这篇关于Groovy:为什么在同一个包中的类需要导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!