我现在正在与其他人一起参与一个 grails 项目。我必须编写一些Java 类。但我需要访问使用 groovy 创建的可搜索对象。看来这个对象必须放在默认包中。
我的问题是:有没有办法从命名包中的 Java 类访问默认包中的这个对象?
最佳答案
You can’t use来自命名包的默认包中的类。
(技术上,您可以通过反射 API,如 Sharique Abdullah 的 answer 所示,但是来自未命名命名空间的类不在范围内 进口报关)
在 J2SE 1.4 之前,您可以使用如下语法从默认包导入类:
import Unfinished;
那就是 no longer allowed 。因此,要从打包类中访问默认包类,需要将默认包类移动到它自己的包中。
如果您有权访问 groovy 生成的源代码,则需要进行一些后处理以将文件移动到专用包中,并在其开头添加此“package”指令。
<小时/>2014 年更新:bug 6975015 ,对于 JDK7 和 JDK8,描述了更严格的禁止从未命名包导入的规定。
<小时/>The
TypeName
must be the canonical name of a class type, interface type, enum type, or annotation type.
The type must be either a member of a named package, or a member of a type whose outermost lexically enclosing type is a member of a named package, or a compile-time error occurs.
"why is [the default package] there in the first place? design error?"
不,这是故意的。
block 引用>
JLS 7.4.2. Unnamed Packages说:“Java SE 平台提供未命名包主要是为了方便开发小型或临时应用程序或刚开始开发时”。
关于java - 如何访问默认包中的java类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14885496/