欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何判断类在需要时才加载?

程序员文章站 2022-03-02 14:17:07
...

   JVM是动态加载,这点同某些静态加载语言不同,但如何证明是动态加载呢?或者说需要时才加载:

 

//: typeinfo/SweetShop.java
// Examination of the way the class loader works.
class Candy {
	static {
		System.out.println("Loading Candy");
	}
}

class Gum {
	static {
		System.out.println("Loading Gum");
	}
}

class Cookie {
	static {
		System.out.println("Loading Cookie");
	}
}

public class SweetShop {
	public static void main(String[] args) {
		System.out.println("inside main");
		new Candy();
		System.out.println("After creating Candy");
		try {
			Class.forName("Gum");
		} catch (ClassNotFoundException e) {
			System.out.println("Couldn’t find Gum");
		}
		System.out.println("After Class.forName(\"Gum\")");
		new Cookie();
		System.out.println("After creating Cookie");
	}
} 
/*
 * Output: inside main Loading Candy After creating Candy Loading Gum After
 * Class.forName("Gum") Loading Cookie After creating Cookie
 */// :~

 

静态初始化块是在类被加载时才会执行,由此证明类对象是在需要时才被加载。

 

You can see from the output that each Class object is loaded only when it’s needed, and the static initialization is performed upon class loading.

相关标签: JVM