人们使用类加载的是什么? [英] What do people use class loading for?

查看:161
本文介绍了人们使用类加载的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,每本Java教科书都会讨论Java的灵活性,因为它可以在运行时加载类。只需拼凑一个字符串并将其提供给 Class.forName(),然后捕获 ClassNotFoundException 并处理它。这个理论非常重要。

So, every Java text book talks about how flexible Java is since it can load classes at run time. Just cobble together a string and give it to Class.forName(), and catch the ClassNotFoundException and handle it. So much for the theory.

你能举例说明你如何使用Java类加载来实现一个本来不可能或不容易的功能吗?请注意,我询问我们可以做什么伟大的事情? - 我正在寻找真实世界的例子,无论是开源应用程序还是 - 如果你能够在不提供太多细节的情况下描述这一点 - 专有应用程序。

Can you give examples of how you've been using Java class loading to achieve a feature which otherwise wouldn't have been possible or easy? Note that I'm not asking "what great things could we do?" - I'm looking for real-world examples, be it an open-source application or - if you can describe this without giving out too much details - a proprietary application.

编辑:当然,VM会根据需要懒惰地加载类。只要我确信我所需要的所有课程都在那里,这就是幕后的事情。如何处理 ClassNotFoundException ?假设我写了十页文本,找不到 PrinterDriver 类。

Sure, the VM loads classes lazily as it needs them. That's a behind-the-scenes thing as long as I'm sure that all classes I'll ever need are there. How do I handle a ClassNotFoundException? Suppose I've written ten pages worth of text, and the PrinterDriver class can't be found.

推荐答案

首先想到的是插件。与C ++这样的语言相比,Java类加载非常容易。

Plugins is the first thing that comes to mind. Java class loading makes it very easy compared to languages like C++.

您可能不知道的一点是,任何Java虚拟机都在很大程度上依赖于内部的类加载。每次字节码解释器看到对方法的引用时,它会检查方法所属的类是否已经加载,如果不加载,则使用类后面的相同机制加载它解析方法之前.forName()。这种机制非常强大,因为任何Java应用程序都真正充当一组可动态加载的可替换组件。如果VM写得很好,它可以通过自定义类加载器加载类,该加载器从网络中取代类而不是常规文件。

One point that you may not be aware of is that any Java virtual machine heavily relies on class loading internally. Everytime a reference to, say, a method is seen by the bytecode interpreter, it checks whether the class the method belongs to is already loaded, and if it is not, loads it using the very same mechanism behind Class.forName() before resolving the method. This mecanism is very powerful as any Java application truly acts as a set of replaceable components which are all dynamically loaded. If the VM is well written it can for instance load classes through a custom class loader that fetches classes from the network instead of regular files.

类加载时间取决于虚拟机实现,但大多数依赖于这种后期绑定机制,它在VM第一次遇到它时加载一个类。

The class loading time depends on the virtual machine implementation, but most rely on this late-binding mechanism that loads a class the first time the VM meets it.

这篇关于人们使用类加载的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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