Java:Class.forName和ClassLoader.loadClass之间的区别

Java:Class.forName和ClassLoader.loadClass之间的区别

问题描述:

最近遇到一些让我思考的代码。有什么区别:

Recently came across some code that got me thinking. What's the difference between:

Class theClass = Class.forName("SomeImpl");
SomeImpl impl = (SomeImpl)theClass.newInstance();

和:

Class theClass = ClassLoader.loadClass("SomeImpl");
SomeImpl impl = (SomeImpl)theClass.newInstance();

它们是同义词吗?在某些情况下,是否优先于另一方?使用这两种方法有什么用,有什么用呢?

Are they synonymous? Is one preferable to the other in certain circumstances? What are the do's and dont's to using these two methods?

提前致谢。

Class.forName()将始终使用调用者的ClassLoader,而ClassLoader.loadClass()可以指定不同的ClassLoader。我相信Class.forName也会初始化加载的类,而ClassLoader.loadClass()方法不会立即执行(它在第一次使用之前不会初始化)。

Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn't do that right away (it's not initialized until it's used for the first time).

在查看确认初始化行为的摘要时刚刚发现了这篇文章。看起来这里有您正在寻找的大部分信息:

Just found this article when looking to confirm my summary of the initialization behavior. It looks like this has most of the information you're looking for:

http://www.javaworld.com/javaworld/javaqa/2003-03/01-qa-0314-forname.html

这个用法很酷,虽然我之前从未使用过它:

This usage is pretty cool, though I've never used it before:

Class.forName(String, boolean, ClassLoader)

它允许您指定ClassLoader并且boolean参数定义是否应该在加载类时初始化类。

It allows you to specify a ClassLoader and the boolean parameter defines whether the class should be initialized when it's loaded or not.