如何访问默认包中的 java 类? [英] How to access java-classes in the default-package?

查看:28
本文介绍了如何访问默认包中的 java 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在和其他人一起在一个 grails 项目中工作.我必须编写一些 Java 类.但我需要访问使用 groovy 创建的可搜索对象.看来,这个对象必须放在默认包中.

我的问题是:有没有办法从命名包中的 Java 类访问默认包中的这个对象?

解决方案

你不能使用 来自命名包的默认包中的类.
(技术上你可以通过反射 API,如 Sharique Abdullah 的 answer 所示,但是 来自未命名命名空间的类不在范围导入声明)

在 J2SE 1.4 之前,您可以使用如下语法从默认包中导入类:

import 未完成;

那是不再允许.因此,要从打包类中访问默认包类,需要将默认包类移动到它自己的包中.

如果您可以访问由 groovy 生成的源代码,则需要进行一些后处理以将文件移动到专用包中并将此包"添加到指令在其开头.


更新 2014:bug 6975015,对于 JDK7 和 JDK8,描述一个偶数更严格禁止从未命名的包导入.

<块引用>

TypeName 必须是类类型、接口类型、枚举类型或注解类型的规范名称.
类型必须是命名包的成员,或者最外层词法封闭类型是命名包的成员的类型的成员,或发生编译时错误.


Andreas 指出 在评论中:

<块引用><块引用>

"为什么 [默认包] 会在那里?设计错误?"

不,这是故意的.
JLS 7.4.2.Unnamed Packages 说:Java SE 平台提供未命名包主要是为了在开发小型或临时应用程序或刚开始开发时提供便利".

I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package.

My question is: Is there a way to access this object in the default-package from a Java-class in a named package?

解决方案

You can’t use classes in the default package from a named package.
(Technically you can, as shown in Sharique Abdullah's answer through reflection API, but classes from the unnamed namespace are not in scope in an import declaration)

Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:

import Unfinished;

That's no longer allowed. So to access a default package class from within a packaged class requires moving the default package class into a package of its own.

If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning.


Update 2014: bug 6975015, for JDK7 and JDK8, describe an even stricter prohibition against import from unnamed package.

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.


Andreas points out in the comments:

"why is [the default package] there in the first place? design error?"

No, it's deliberate.
JLS 7.4.2. Unnamed Packages says: "Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development".

这篇关于如何访问默认包中的 java 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆