Java有包名的类不能引用默认包中的类?用反射机制解决!

        加入有一个类不加package名就属于默认包,如果有一个类有包名那么如何引用那个默认包里的类呢?各种import都不行, Eclipse也无法自动引入。
       其实,从 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


那么怎样才能非默认包里的类调用默认包里的类呢?这里要用到反射机制。

假如class A 在默认包里

class A {

       public void say() {

          System.out.println("Hello World!");

      }

      public void speek(String s) {

         System.out.println(s);

     }

}

class B在非默认包里,class B要调用class A的方法则:


class B {

      public static void main(String[] args) {

             Class c = Class.forName("A");

     Method m = c.getDeclaredMethod("say",null);//得到A中声明为say的方法

     m.invoke(c.newInstance());

     m = c.getDeclaredMethod("speek", String.class);//得到A中声明为speek的方法

     m.invoke(c.newInstance(), "Hi~");

     }

}


如果有看不懂的地方请自行查API文档。

你可能感兴趣的:(JAVA)