动态加载jar 并进行调用

来源:互联网 发布:网络课程怎么挂着 编辑:程序博客网 时间:2024/06/05 01:17

动态加载jar 并进行调用

像Eclipse它的所有插件的.jar文件都是放在plugin目录下,我们的程序如果也要做成可扩展插件形式plugins

在java中如何简单的实现这个功能。 
1、建立一个工程,并为其增加一个 Interface,命名为ActionInterface.java。该接口为使用者公开了一个方法,你定义的插件必须实现这个接口

如下:  

package org.junesky.classPathTest;public interface ActionInterface {     public String action(); }
  

编译后,将该工程打包为.jar文件。 
打包方法: 

1,myeclipse 中直接导出

2.在包的顶级目录(也就是例子中的org所在的目录)建立一个名为MANIFEST.MF的文件,键入:Manifest-Version: 1.0保存。 
在ms-doc窗口中键如命令:jar cvfm classLoader.jar MANIFEST.MF org/ 
其中classLoader.jar是打包后的文件名,org/是path。 

2、建立一个新工程,将classLoader.jar导入,新建class文件MyAction并实现ActionInterface。如下: 

程序代码 

package org.junesky. MyAction; import org.junesky.classPathTest. ActionInterface; public class MyActionimplements ActionInterface {     public String action() {         // TODO Auto-generated method stub         return "------------------ok";    }}

编译后打包为classTest.jar。 

3、新建一工程,将classLoader.jar和classTest.jar导入,新建class文件MyClassLoader.java并继承URLClassLoader。如下: 

程序代码 

package org.junesky.classPathTest; import   java.net.URL;import   java.net.URLClassLoader; import org.junesky.classPathTest. ActionInterface;  public class ClassPathTestextends URLClassLoader {     public ClassPathTest(URL url) {         super(new URL[] { url });     }     public static Object test(String str , String cls) {         try {            URL url = new URL(str);            ClassPathTest t = new ClassPathTest(url); Class c = t.findClass(cls); ActionInterface action = (ActionInterface)c.newInstance();  return action.action();        }catch (Exception ex) {             ex.printStackTrace();        }        return "";    }     public static void main(String[] args) {         try {                        System.out.println(                ClassPathTest.test("file:D:/JavaTest/ClassTest2/lib/ MyAction.jar",                        "org.junesky. MyAction. MyAction "));         }catch (Exception ex) {             ex.printStackTrace();        }    }}

编译通过执行,会看到控制台上打印出: 

------------------ok 

总结:

首先,我们创建了一个接口ActionInterface,在利用URLClassLoader. findClass后,以这个接口创建对象的实例。

在第二个jar文件中,我们创建了MyAction.java并实现了ActionInterface,在方法action中我们返回了一个字符串。

接下来,我们利用URLClassLoader加载D:/JavaTest/ClassTest2/lib/ MyAction.jar,并以findClass查找并加载org.junesky. MyAction. MyAction类,为得到的Class生成实例: 

Class c = t.findClass(cls);  // 加载类 ActionInterface action = (ActionInterface)c.newInstance();  // 生成对象实例 

最后调用ActionInterface中声明的action方法打印出MyAction中返回的字符串。

0 0
原创粉丝点击