publicstatic Class<?> forName(String className)
Returns the Class object associated withthe class or interface with the given string name. Invokingthis method is equivalent to:
Class.forName(className,true, currentLoader)
where currentLoader denotes the definingclass loader of the current class.
For example, thefollowing code fragment returns the runtime Class descriptor for theclass named java.lang.Thread:
Class t =Class.forName("java.lang.Thread")
A call to forName("X") causes theclass named X to beinitialized.
Parameters:
className - the fully qualifiedname of the desired class.
Returns:
the Class object for the classwith the specified name.
从官方给出的API文档中可以看出:
Class.forName(className)实际上是调用Class.forName(className,true, this.getClass().getClassLoader())。第二个参数,是指Class被loading后是不是必须被初始化。可以看出,使 用Class.forName(className)加载类时则已初始化。
所以Class.forName(className)可以简单的理解为:获得字符串参数中指定的类,并初始化该类。
在初始化一个类,生成一个实例的时候,newInstance()方法和new关键字除了一个是方法,一个是关键字外,它们的区别在于创建对象的方式不一样,前者是使用类加载机制,后者是创建一个新类。
从JVM的角度看,我们使用关键字new创建一个类的时候,这个类可以没有被加载。但是使用newInstance()方法的时候,就必须保证:
1、这个类已经加载;
2、这个类已经连接了。
而完成上面两个步骤的正是Class的静态方法forName()所完成的,这个静态方法调用了启动类加载器,即加载
java API的那个加载器。