类加载--- JAVA动态性

[color=brown]类加载学习 [/color]
[color=orange]隐式动态性[/color]
也就是说当自己的程序用到NEW关键字时,就会载入需要载入的类....

[color=red]显示的动态性[/color]
1. 一个是由java.lang.Class 的forName()方法
2.是由java.lang.ClassLoader 的loadClass()方法


写例子让自己理解下;
[code]
interface Assembly{
public void start();
}
public class Main{
public static void main (String[] args) throws Exception{
Class c=Class.forName(args[0]);
Object o=c.newInstance();
Assembly a=(Assembly) o;
a.start();
}
}
class A implements Assembly{
public void start(){
System.out.println("class a 使用して");
}
}
class B implements Assembly{
public void start(){
System.out.println("class b 使用して");
}
}
class C implements Assembly{
public void start(){
System.out.println("class c 使用して");
}
}
[/code]
动态载入,用到哪个类的时候就载入哪个类.

执行 java -verbose:class Main
[code]
[Loaded Main from file:/C:/wang/]
[Loaded java.lang.IndexOutOfBoundsException from shared objects file]
[Loaded java.lang.ArrayIndexOutOfBoundsException from shared objects file]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:6)
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file]
[/code]
抛出异常了,界限异常.. 没有输入命令行参数......

接着 java -verbose:class Main A
[code]
[Loaded java.security.cert.Certificate from shared objects file]
[Loaded Main from file:/C:/wang/]
[Loaded Assembly from file:/C:/wang/]
[Loaded A from file:/C:/wang/]
class a 使用して
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file][/code]
先载入主类.. 接口...
载入A类,即可以在不修改主类的情况下增加新的功能..(我没把类分开写.....)

如果写个类D继承了类A ... 会如何..
[code]
class D extends A implements Assembly{
public void start(){
System.out.println("class d extends a implements assembly 使用して");
}
}
[/code]

接着: java -verbose:class Main D
[code]
[Loaded Main from file:/C:/wang/]
[Loaded Assembly from file:/C:/wang/]
[Loaded A from file:/C:/wang/]
[Loaded D from file:/C:/wang/]
class d extends a implements assembly 使用して
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file]
[/code]
哦. 是先载入了父类的文件,再载入了子类.....

如果D->C->B->A 依此继承....
[code]
[Loaded Main from file:/C:/wang/]
[Loaded Assembly from file:/C:/wang/]
[Loaded A from file:/C:/wang/]
[Loaded B from file:/C:/wang/]
[Loaded C from file:/C:/wang/]
[Loaded D from file:/C:/wang/]
class d extends a implements assembly 使用して
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file]
[/code]
就按循序载入....
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值