类加载--- JAVA动态性

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

  显示的动态性
1. 一个是由java.lang.Class 的forName()方法
2.是由java.lang.ClassLoader 的loadClass()方法


写例子让自己理解下;
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 使用");
    }
}


动态载入,用到哪个类的时候就载入哪个类.

执行 java -verbose:class Main

[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]


抛出异常了,界限异常..  没有输入命令行参数......

接着 java -verbose:class Main A

[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]


先载入主类.. 接口...
载入A类,即可以在不修改主类的情况下增加新的功能..(我没把类分开写.....)

如果写个类D继承了类A ...  会如何..

class D extends A implements Assembly{
    public void start(){
        System.out.println("class d extends a implements assembly 使用して");
    }
}

接着: java -verbose:class Main D

[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]


哦. 是先载入了父类的文件,再载入了子类.....

如果D->C->B->A 依此继承....

[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]


就按循序载入....

你可能感兴趣的:(java,C++,c,C#,Security)