Class clazz = Class.forName(className);
与
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class clazz = cl.loadClass(className);
是两种载入类的方式。那么这两种方式有什么不同呢?直接看源码来的快。
ClassLoader.loadClass(),也就是第二种方式。最后执行的是下面这个方法
loadClass(name, false)那么第二个参数false有什么用呢?看注释if true then resolve the class,resolve又是执行了什么操作呢?
看注释这个方法是Links the specified class.那么Links又是什么操作呢, http://blog.sina.com.cn/s/blog_4fe01e630100gu3x.html 这篇文章讲的很清楚。
最后总结下:
Class的装载包括3个步骤:加载(loading),连接(link),初始化(initialize).
Class.forName(className) 执行了这3个步骤,也就是初始化了这个类;而ClassLoader.loadClass(className)则只是loading class。另外ClassLoader.loadClass(className,true)加载的类对象是在第一次被调用时才进行初始化的;当然我认为这里的参数应该是true,只有执行了前2步才能初始化。
与
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class clazz = cl.loadClass(className);
是两种载入类的方式。那么这两种方式有什么不同呢?直接看源码来的快。
class.forName(className)的源码
public static Class<?> forName(String className)
throws ClassNotFoundException {
return forName0(className, true, ClassLoader.getCallerClassLoader());
}
Class.forName(className)实际上是调用Class.forName(className, true, this.getClass().getClassLoader())。第二个参数,是指Class被loading后是不是必须被初始化。可以看出,使用class.forName(className)加载类是则已初始化。想到了JDBC中的Driver注册。
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbcurl");
//Driver类中注册自己到DriverManager,static代码块是在类初始化时执行的。
// Register ourselves with the DriverManager
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
ClassLoader.loadClass(),也就是第二种方式。最后执行的是下面这个方法
loadClass(name, false);
name The binary name of the class
resolve If true then resolve the class
protected synchronized Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First, check if the class has already been loaded
Class c = findLoadedClass(name);
if (c == null) {
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClass0(name);
}
} catch (ClassNotFoundException e) {
// If still not found, then invoke findClass in order
// to find the class.
c = findClass(name);
}
}
if (resolve) {
resolveClass(c);//resolve class
}
return c;
}
loadClass(name, false)那么第二个参数false有什么用呢?看注释if true then resolve the class,resolve又是执行了什么操作呢?
Links the specified class.
protected final void resolveClass(Class<?> c) {
check();// Check to make sure the class loader has been initialized.
resolveClass0(c);
}
看注释这个方法是Links the specified class.那么Links又是什么操作呢, http://blog.sina.com.cn/s/blog_4fe01e630100gu3x.html 这篇文章讲的很清楚。
最后总结下:
Class的装载包括3个步骤:加载(loading),连接(link),初始化(initialize).
Class.forName(className) 执行了这3个步骤,也就是初始化了这个类;而ClassLoader.loadClass(className)则只是loading class。另外ClassLoader.loadClass(className,true)加载的类对象是在第一次被调用时才进行初始化的;当然我认为这里的参数应该是true,只有执行了前2步才能初始化。