Java ClassLoader委派模型的好处? [英] Benefits of Java ClassLoader delegation model?

查看:168
本文介绍了Java ClassLoader委派模型的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道ClassLoader首先检查是否已加载该类,如果没有,则立即将此检查委托给其父ClassLoader.But,最后所有类都由Bootstrap加载。我们为什么要委托我们实现的目标是什么?

As I know that ClassLoader first check if the class has been loaded, if not then immediately delegate this check to its parent ClassLoader.But at the end all the classes are loaded by the Bootstrap. why we are delegating and what are benefits we are achieving by this ?

推荐答案

实现不必总是委托给父类加载器。这取决于要求。如果需要一个类应该由类加载器实现加载,它可以加载它,即使它已经被另一个类加载器加载了。

Implementation need not always delegate to parent class loader. It depends on the requirement. If requirements needs that a class should be loaded by the class loader implementation, it can load it, even if its already loaded by another class loader.

一个类(和实例) )由ClassLoader_1加载的内容将无法被另一个ClassLoader_2加载的实例访问。这提供了额外的安全性。

A class (and instances) loaded by ClassLoader_1 will not be accessible by instance loaded by another ClassLoader_2. This provides additional security.

例如,在浏览器中,每个域都可以被赋予自己独特的类加载器(通过浏览器实现)。核心java类可以委托给Boot Class加载器来优化核心类,因为它们不会有所不同。并且所有这些类加载器都可以加载到单个JVM中以便最佳地使用资源。

For example, in a browser, each domain can be given their own unique classloader (by the browser implementation). The core java classes can be delegated to Boot Class loader to optimize core classes as they wont be different. And all these class loaders can loaded inside a single JVM for optimal use of resources.

现在,一个域的实例/类将无法访问其他域的实例由另一个类加载器加载。如果他们访问跨站点,他们将收到ClassCastException。

Now, instances/classes of one domain wont be able access instances of other domain which are loaded by another class loader. They will receive ClassCastException if they access cross site.

层次结构确保父级加载的类与子级兼容

Hierarchy ensures that classes loaded by parent are compatible across children

您可以使用以下命令从执行线程访问当前上下文类加载器

You can access current context class loader from the execution Thread using following

Thread.getContextClassLoader();

您可以使用以下

Object o = ....
o.getClass().getClassLoader();

这篇关于Java ClassLoader委派模型的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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