浅学JAVA类加载

Java ClassLoader
Java的类加载器是个什么,如何运做... 学习下.

类加载器使J具有动态性,J程序是由许多类组成,每个类生成一个文件,互相对应.
执行时JVM找到J程序需要的类并载入内存.
就是把硬盘的.CLASS文件复制一份到内存中,并初始化

例:
class A{
   public void print(){
       System.out.println("class A");
   }
}
class B{
    public void print(){
        System.out.println("class B");
    }
}

public class Main{
    public static void main (String[] args){
       A a=new A();
       a.print();
       B b=new B();
       b.print();
    }
}


执行 java -verbose:class Main

[Loaded java.io.FilePermission from shared objects file]
[Loaded java.io.FilePermission$1 from shared objects file]
[Loaded java.io.FilePermissionCollection from shared objects f
[Loaded java.security.AllPermission from shared objects file]
[Loaded java.security.UnresolvedPermission from shared objects
[Loaded java.security.BasicPermissionCollection from shared ob
[Loaded java.security.Principal from shared objects file]
[Loaded java.security.cert.Certificate from shared objects fil
[Loaded Main from file:/C:/wang/]
[Loaded A from file:/C:/wang/]
class A
[Loaded B from file:/C:/wang/]
class B
[Loaded java.lang.Shutdown from shared objects file]
[Loaded java.lang.Shutdown$Lock from shared objects file]


先把核心类库载入内存,然后可以清楚的看到载入了J程序的类Main.class,A.class
B.class到内存中.

当然,如果程序中先new一个B的对象调用print方法,在new个A的对象调用print方法,
就是载入Main.class,B.class,A.class

java.exe找到JRE,运行时环境执行.class文件.

  預先载入,按需求載入

在自己写的类中,B.class和A.class在用到这些类的时候才回被载入...

把程序B实例化的例子和调用方法的语句注释后,B类就不会被载入.

[Loaded Main 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类和主类.

不管如何,总会载入JAVA的基础类库,既JAVA程序必须的类,预先载入.
自己写的类载入就是按需求载入.

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