细节决定成败:java中,是不是无法import默认包中的类?

来源:互联网 发布:电信网络诈骗论文 编辑:程序博客网 时间:2024/05/19 04:27

假如有一个类,直接不加package,也就是属于默认包:

另外一个类,处于com包(或者任何非默认包),如何使用上面这个属于默认包的类?



import *;
import *.*;
import ClassInDefaultPackage;
都不行,Eclipse也无法自动引入。

是java特性规定无法引用默认包的类吗?

 

其实,从 J2SE 1.4 开始,Java 编译器不再支持 import 进未命包名的类、接口。

详见 J2SE 1.4 与 J2SE 1.3 兼容性文档,第 8 点第二部分:

http://java.sun.com/javase/compatibility_j2se1.4.html

The compiler now rejects import statements that import a type from the unnamed namespace. Previous versions of the compiler would accept such import declarations, even though they were arguably not allowed by the language (because the type name appearing in the import clause is not in scope). The specification is being clarified to state clearly that you cannot have a simple name in an import statement, nor can you import from the unnamed namespace.

To summarize, the syntax

    import SimpleName;

is no longer legal. Nor is the syntax

    import ClassInUnnamedNamespace.Nested;

which would import a nested class from the unnamed namespace. To fix such problems in your code, move all of the classes from the unnamed namespace into a named namespace.

而至于为什么 unnamed package 还没有被去除掉?因为这可以很方便地编写一些小程序,也可以方便初学者进行学习。


http://java.sun.com/docs/books/jls/third_edition/html/packages.html#7.4.2

 

那么,非默认包是可以调用到默认包里的类呢?

 

答案是肯定的,但这里要用到反射。比如:
在默认包里有个类:


而如果你想再包test下的类中调用disp()方法可以这样:
  

 

此文资料来自CSDN论坛,经个人整理成文,特此声明

原创粉丝点击