package example; 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 Test { public static void main(String[] args){ System.out.println("inside main"); new Candy(); System.out.println("After Creating Candy"); try { Class.forName("example.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"); } }
输出:
inside main
loading Candy
After Creating Candy
loading Gum
After Class.forname("Gum")
loading Cookie
After Creating Cookie
static初始化是在类加载时进行的
Class.forname()方法是class类一个static成员,是取得Class对象的引用的一种方法。
如果类Gum还没被加载就加载他,在加载过程中,static字句执行