Difference between Class.forName() and ClassLoader.loadClass()

Both methods try to dynamically locate and load ajava.lang.Classobject corresponding to a given class name. However, their behavior differs regarding whichjava.lang.ClassLoaderthey use for class loading and whether or not the resultingClassobject is initialized.

The most common form ofClass.forName(), the one that takes a singleStringparameter, always uses thecaller'sclassloader. This is the classloader that loads the code executing theforName()method. By comparison,ClassLoader.loadClass()is an instance method and requires you to select a particular classloader, which may or may not be the loader that loads that calling code. If picking a specific loader to load the class is important to your design, you should useClassLoader.loadClass()or the three-parameter version offorName()added in Java 2 Platform, Standard Edition (J2SE):Class.forName(String, boolean, ClassLoader).

Additionally,Class.forName()'s common form initializes the loaded class. The visible effect of this is the execution of the class's static initializers as well as byte code corresponding to initialization expressions of all static fields (this process occurs recursively for all the class's superclasses). This differs fromClassLoader.loadClass()behavior, which delays initialization until the class is used for the first time.

You can take advantage of the above behavioral differences. For example, if you are about to load a class you know has a very costly static initializer, you may choose to go ahead and load it to ensure it is found in the classpath but delay its initialization until the first time you need to make use of a field or method from this particular class.

The three-parameter methodClass.forName(String, boolean, ClassLoader)is the most general of them all. You can delay initialization by setting the second parameter tofalseand pick a given classloader using the third parameter. I recommend always using this method for maximum flexibility.

Class initialization errors are tricky

Just because you successfully load a class does not mean there won't be any more problems. Recollect that static initialization code can throw an exception, and it will get wrapped in an instance ofjava.lang.ExceptionInInitializerError, at which point, the class becomes unusable. Thus, if it is important to process all such errors at a known point in code, you should use aClass.forName()version that performs initialization.

Furthermore, if you handleExceptionInInitializerErrorand take measures so that the initialization can be retried, it will likely not work.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值