User.java
public class User { private static int a = 10; { System.out.println("普通代码块.."); } static { System.out.println("静态变量" + a); System.out.println("静态代码块.."); } }
TestClassLoad.java
public class TestClassLoad { public static void main(String[] args) throws ClassNotFoundException { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); Class<?> loadUser = systemClassLoader.loadClass("User"); String name = loadUser.getName(); System.out.println(name); System.out.println("-------------------"); Class<?> forName = Class.forName("User"); String name2 = forName.getName(); System.out.println(name2); } }
运行结果:
User
-------------------
静态变量10
静态代码块..
User
说明:区别在于,通过 Class.forName 加载类会 执行 静态方法。