我现在和其他人一起在一个 grails 项目中工作。我必须编写一些 Java 类。但我需要访问用 groovy 创建的可搜索对象。看来,这个对象必须放在默认包中。
我的问题是:有没有办法从命名包中的 Java 类访问默认包中的这个对象?
最佳答案
You can’t use来自命名包的默认包中的类。
(技术上您可以,如 Sharique Abdullah 的 answer 中所示,通过反射 API,但是来自未命名命名空间的类不在范围内 进口声明)
在 J2SE 1.4 之前,您可以使用如下语法从默认包中导入类:
import Unfinished;
那是 no longer allowed .因此,要从打包类中访问默认包类,需要将默认包类移动到它自己的包中。
如果您可以访问 groovy 生成的源代码,则需要进行一些后处理以将文件移动到专用包中并在其开头添加此“包”指令。
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?"
不,这是故意的。
JLS 7.4.2. Unnamed Packages说:“Java SE 平台提供了未命名的包,主要是为了方便开发小型或临时应用程序或刚开始开发时”。
关于java - 如何访问默认包中的 java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/283816/