如何创建可插入的Java程序? [英] How to create a pluginable Java program?

查看:108
本文介绍了如何创建可插入的Java程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以使用插件扩展的Java程序。我该怎么做?我应该在哪里寻找?

I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?

我有一套插件必须实现的接口,它应该在一个jar中。该程序应该在相对(程序)文件夹中监视新罐并以某种方式注册它们。

I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.

虽然我做就像Eclipse RCP一样,我认为这对我的简单需求来说太过分了。

Although I do like Eclipse RCP, I think it's too much for my simple needs.

同样的事情适用于Spring,但是因为无论如何我都要去看它,我不妨试试吧。

Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.

但是,我仍然希望找到一种方法来尽可能简单地创建我自己的插件框架。

But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.

推荐答案

我已经为过去编写的软件做过这个,非常方便。我首先创建了一个接口,我需要实现所有插件类。然后我使用Java ClassLoader 加载那些类和创建它们的实例。

I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java ClassLoader to load those classes and create instances of them.

你可以采用的一种方法是:

One way you can go about it is this:

File dir = new File("put path to classes you want to load here");
URL loadPath = dir.toURI().toURL();
URL[] classUrl = new URL[]{loadPath};

ClassLoader cl = new URLClassLoader(classUrl);

Class loadedClass = cl.loadClass("classname"); // must be in package.class name format

已加载类,现在需要创建它的一个实例,假设接口名称为MyModule:

That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule:

MyModule modInstance = (MyModule)loadedClass.newInstance();

这篇关于如何创建可插入的Java程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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