使用 ClassLoader 和 Class.forName 加载类的区别 [英] Difference between Loading a class using ClassLoader and Class.forName

查看:25
本文介绍了使用 ClassLoader 和 Class.forName 加载类的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 2 个代码片段

Below are 2 code snippets

第一个使用 ClassLoader 类加载指定的类

ClassLoader cls = ClassLoader.getSystemClassLoader();Class someClass = cls.loadClass("TargetClass");

第二个使用 Class.forName() 加载指定的类

Class cls = Class.forName("TargetClass");

上述方法之间有什么区别.哪个用于哪个目的?

What is the difference between the above said approaches. Which one serves for which purpose?

推荐答案

快速解答(不含代码示例)

Quick answer (without code samples)

使用显式ClassLoader cls = <a ClassLoader>; 方法,您可以灵活地从不是默认 ClassLoader 的 ClassLoader 加载类.在您的情况下,您使用的是默认的 System ClassLoader,因此它提供了与 Class.forName(String name) 调用相似的总体结果(带有最终对象差异的实例化),但是您 可以引用另一个类加载器.

With the explicit ClassLoader cls = <a ClassLoader>; approach you have the flexibility of loading the class from a ClassLoader that is not your default ClassLoader. In your case you're using the default System ClassLoader, so it gives the similar overall result (with an instantiation of the final object difference) as the Class.forName(String name) call, but you could reference another ClassLoader instead.

也就是说,你也可以使用 Class.forName(String name, boolean initialize, ClassLoader loader),只要你知道 ClassLoader 是什么.

That said, you can also use Class.forName(String name, boolean initialize, ClassLoader loader) as long as you know what that ClassLoader is.

例如,基于 EAR 的应用程序有自己的类加载器,其中包含一个 XML 解析库版本.您的代码通常使用这些类,但在一个实例中,您需要从库的早期版本(应用服务器碰巧在其整个 ClassLoader 中保存的)获取反序列化类.因此,您可以改为引用该应用程序服务器类加载器.

For example, your EAR based application has its own ClassLoader with a version of an XML Parsing library wrapped inside of it. Your code normally uses those classes, but in one instance you need to grab a deserialisation class from an earlier version of the library (that the Application Server happens to be holding in its overall ClassLoader). So you could reference that Application Server ClassLoader instead.

不幸的是,在我们获得 Jigsaw (JDK 8) 项目之前,它的使用频率超过了我们的预期:-)

Unfortunately until we get project Jigsaw (JDK 8) this is used more often than we'd like :-)

这篇关于使用 ClassLoader 和 Class.forName 加载类的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆