转(无法导入默认包)
假如有一个类,直接不加package,也就是属于默认包:
view plaincopy to clipboardprint?
public class ClassInDefaultPackage {
public void doSomething(){
System.out.println("I am in default package.");
}
}
public class ClassInDefaultPackage {
public void doSomething(){
System.out.println("I am in default package.");
}
}
另外一个类,处于com包(或者任何非默认包),如何使用上面这个属于默认包的类?
view plaincopy to clipboardprint?
package com;
import ??;
public class ClassInComPackage {
public static void main(String[] args){
ClassInDefaultPackage obj=new ClassInDefaultPackage();
obj.doSomething();
}
}
package com;
import ??;
public class ClassInComPackage {
public static void main(String[] args){
ClassInDefaultPackage obj=new ClassInDefaultPackage();
obj.doSomething();
}
}
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
那么,非默认包是可以调用到默认包里的类呢?
答案是肯定的,但这里要用到反射。比如:
在默认包里有个类:
view plaincopy to clipboardprint?
public class DefaultPackage {
public void disp() {
System.out.println("Hello World!");
}
}
public class DefaultPackage {
public void disp() {
System.out.println("Hello World!");
}
}
而如果你想再包test下的类中调用disp()方法可以这样:
view plaincopy to clipboardprint?
package test;
import java.lang.reflect.*;
public class TestDefaultPackage {
public static void main(String[] args) throws Exception {
Class c = Class.forName("DefaultPackage");
Method m = c.getDeclaredMethod("disp", null);
m.invoke(c.newInstance(), null);
}
}
package test;
import java.lang.reflect.*;
public class TestDefaultPackage {
public static void main(String[] args) throws Exception {
Class c = Class.forName("DefaultPackage");
Method m = c.getDeclaredMethod("disp", null);
m.invoke(c.newInstance(), null);
}
}
此文资料来自CSDN论坛,经个人整理成文,特此声明
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/apei830/archive/2009/08/31/4503112.aspx