java sun包无法引用_Java有包名的类不能引用默认包中的类?用反射机制解决! | 学步园...

加入有一个类不加package名就属于默认包,如果有一个类有包名那么如何引用那个默认包里的类呢?各种import都不行,Eclipse也无法自动引入。

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

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

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 还没有被去除掉?因为这可以很方便地编写一些小程序,也可以方便初学者进行学习。

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

假如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文档。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值