java urlclassloader 的用法。只有在极少数情况下才需要吗?

发布于 2024-10-10 02:21:08 字数 491 浏览 0 评论 0原文

在这种情况下,可以使用 URLClassLoader 从指定路径中的特定 jar 加载类?
例如,

URL url = new URL("file:///path/to/customClasses.jar");
URLClassLoader pluginLoader = new URLClassLoader(new URL[] { url });
Class<?> cl = pluginLoader.loadClass("apackage.MyCustomClass");

如果我想使用 customClasses.jar 中的类,我一直认为将此 jar 放在可从 CLASSPATH 访问的路径中就足够了。
然后在我的代码中只需使用 apackage.MyCustomClass
我想我在这里有一些误解或遗漏的地方,所以有人可以解释一下并举一个例子,说明上面这种方式加载类的片段何时有用?
谢谢!

In which case one would use a URLClassLoader to load a class from a specific jar in a specified path?
E.g.

URL url = new URL("file:///path/to/customClasses.jar");
URLClassLoader pluginLoader = new URLClassLoader(new URL[] { url });
Class<?> cl = pluginLoader.loadClass("apackage.MyCustomClass");

If I wanted to use classes from customClasses.jar, I always thought that placing this jar in a path accesible from CLASSPATH is enough.
Then in my code just use apackage.MyCustomClass.
I think I have something missunderstood or missing here, so could someone please explain and give an example of when the above snippet of loading class this way is useful?
Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉宸 2024-10-17 02:21:08

我想说,根据您正在进行的编程类型,URLClassLoader 的使用应该是非常罕见的。

通常,您将使用类加载器在运行时加载您无法提前预料到的类。

一个很好的例子是,如果您构建一个可以使用插件扩展的工具,并且插件在运行时加载。例如,Eclipse。

如果您在编译时有可用的 jar 并且位于命令行上,请将所需的 jar 文件添加到编译语句中。例如,

javac -cp /path/to/lib/customClasses.jar MyClassThatReferencesCustomClasses

如果您使用的是 Eclipse,请将 jar 添加到您的项目中,然后右键单击它并选择“添加到构建路径”。

问候,

威尔

I would say that depending on the type of programming you are doing, the use of the URLClassLoader should be a very rare occurrence.

Typically you will use the class loader for loading in classes at runtime that you couldn't anticipate in advance.

A good example is if you build a tool that can be extended with plugins, and the plugins are loaded at runtime. For example, Eclipse.

If you have the jar available at compile time and are on a command line, add the needed jar file to your compile statement. For example,

javac -cp /path/to/lib/customClasses.jar MyClassThatReferencesCustomClasses

If you're using Eclipse, add the jar to your project, and right click on it and select add to build path.

Regards,

Will

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文