在Java中动态加载模块(类)的最佳方法 [英] Best approach to dynamically load modules (classes) in Java

查看:474
本文介绍了在Java中动态加载模块(类)的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写一个需要在不同类型的设备上运行的应用程序。我的方法是创建一个模块化应用程序,它可以根据操作所需的设备动态加载不同的类。

I'm currently writing an application that requires to operate on different type of devices. My approach would be to make a "modular" application that can dynamically load different classes according to the device they need to operate on.

为了使应用程序易于扩展,我的目标是为附加模块(.jar或.class文件)分配特定路径,使核心程序保持原样。当不同的客户需要不同的模块时(不必为每个模块编译不同的应用程序),这将是至关重要的。

To make the application easily extensible, my goal is to assign a specific path to the additional modules (either .jar or .class files) leaving the core program as it is. This would be crucial when having different customers requiring different modules (without having to compile a different application for each of them).

这些模块将实现一个通用接口,而核心应用程序可以使用接口上定义的这些方法,让单个实现完成工作。 根据需要加载它们的最佳方式是什么?我正在考虑使用URLClassLoader,但我不知道这种方法是否是根据新的模式和Java趋势是最新的,就像我想的那样喜欢避免设计不良的应用程序和弃用的技术。 使用JDK 9制作模块化且易于扩展的应用程序的另一种最佳方法(只需将模块文件添加到文件夹即可扩展)?

These modules would implement a common interface, while the "core" application can use these methods defined on the interface and let the single implementations do the work. What's the best way to load them on demand? I was considering the use of URLClassLoader but i don't know if this approach is up-to-date according to new patterns and Java trends, as I would like to avoid a poorly designed application and deprecated techniques. What's an alternative best approach to make a modular and easily extensible application with JDK 9 (that can be extended just by adding module files to a folder) ?

推荐答案

听起来您可能想要使用 ServicerLoader 接口,自Java 6以来一直可用。但请记住,如果你想使用Spring依赖注入,这可能不是你想要的。

It sounds like you might want to use the ServicerLoader interface, which has been available since Java 6. However, bear in mind that, if you want to use Spring dependency injection, this is probably not what you want.

这篇关于在Java中动态加载模块(类)的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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