您的位置:首页 > 编程语言 > Java开发

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

2009-08-31 13:15 483 查看
假如有一个类,直接不加package,也就是属于默认包:

]public class ClassInDefaultPackage {

public void doSomething(){
System.out.println("I am in default package.");
}
}


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

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
 

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

 

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

public class DefaultPackage {
public void disp() {
System.out.println("Hello World!");
}
}

而如果你想再包test下的类中调用disp()方法可以这样:
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论坛,经个人整理成文,特此声明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息