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

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

问题描述

以下是2个代码段

第一个使用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。在您的情况下,您使用的是默认的System ClassLoader,因此它给出了类似的整体结果(最终对象差异的实例化),如 Class.forName(String name)调用,但你可以引用另一个ClassLoader。

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(字符串名称,布尔初始化,ClassLoader加载器)只要你知道那个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 Parsing库版本的ClassLoader。您的代码通常使用这些类,但在一个实例中,您需要从早期版本的库中获取反序列化类(Application Server恰好在整体ClassLoader中)。所以你可以改为引用那个Application Server 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天全站免登陆