假如有一个类,直接不加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论坛,经个人整理成文,特此声明
本文探讨了Java中如何从非默认包引用默认包内的类。由于J2SE1.4开始,编译器不再支持直接导入未命名空间的类,故需通过反射机制实现跨包调用。
1305

被折叠的 条评论
为什么被折叠?



