Class.forName()源码如下:
/**Returns the {@code Class} object associated with the class or
*interface with the given string name. Invoking this method is
* equivalent to:
Class.forName(className, true, currentLoader)
*/
public
static
Class<?> forName(String className)
throws
ClassNotFoundException {
return
forName0(className,
true
, ClassLoader.getCallerClassLoader());
}
从官方给出的API文档中可以看出:
Class.forName(className)实际上是调用Class.forName(className,true, this.getClass().getClassLoader())。第二个参数,是指Class被loading后是不是必须被初始化。可以看出,使用Class.forName(className)加载类时则已初始化。
所以Class.forName(className)可以简单的理解为:获得字符串参数中指定的类,并初始化该类。
Class.forName(className).
newInstance() 和 new的区别
1.创建方式不一样,前者是使用类加载机制,后者是创建一个新类。
2.newInstance()实际上是把new这个方式分解成两步:首先用class加载某个类,然后再实例化。
3. newInstance: 弱类型。低效率。只能调用无参构造。
new: 强类型。相对高效。能调用任何public构造。