URLClassLoader使用方法及事例程序

来源:互联网 发布:网络博客评级 编辑:程序博客网 时间:2024/04/30 07:38

参考文献:http://blog.csdn.net/shixin1198/article/details/3733948

1.使用概要:

File file = new File(jar文件全路径);
URL url = file.toURL();
URLClassLoader loader = new URLClassLoader(new URL[] { url });
Class tidyClazz = loader.loadClass(所需class的含包名的全名);

2.详细说明:

我们知道,Java利用ClassLoader将类载入内存,并且在同一应用中,可以有很多个ClassLoader,通过委派机制,把装载的任务传递给上级的装载器的,依次类推,直到启动类装载器(没有上级类装载器)。如果启动类装载器能够装载这个类,那么它会首先装载。如果不能,则往下传递。当父类为null时,JVM内置的类(称为:bootstrap class loader)就会充当父类。想想眼下的越来越多用XML文件做配置文件或者是描述符、部署符。其实这些通过XML文档描述的配置信息最终都要变成Java类,基实都是通过ClassLoader来完成的。URLClassLoader是ClassLoader的子类,它用于从指向 JAR 文件和目录的 URL 的搜索路径加载类和资源。也就是说,通过URLClassLoader就可以加载指定jar中的class到内存中。
下面来看一个例子,在该例子中,我们要完成的工作是利用URLClassLoader加载jar并运行其中的类的某个方法。
(1)创建java project:URLClassLoaderTest0,定义一个接口,使所有继承它的类都必须实现action方法,如下:
package uRLClassLoaderTest0;//定义接口ActionInterfacepublic interface ActionInterface {public String action();}
完成后将其打包为testInterface.jar文件。
(2)接下来新建java project:URLClassLoaderTest1,为了编译通过,引入之前打好的testInterface.jar包。并创建TestAction类,使它实现ActionInterface接口。如下:
package uRLClassLoaderTest1;import uRLClassLoaderTest0.ActionInterface;//在项目中导入testInterface.jar这个包,实现接口ActionInterface.jar包名不能为类名public class TestAction implements ActionInterface {public String action() {return "this ActionTest class";}}
完成后将其打包为test.jar,放在d盘根目录下。下面要做的就是利用URLClassLoader加载并运行TestAction的action方法,并将返回的值打印在控制台上。
(3)新建java project:URLClassLoaderTest2,引入testInterface.jar包。并创建一可执行类(main方法),在其中加入如下代码:
package uRLClassLoaderTest2;import java.net.*;import java.io.*;import uRLClassLoaderTest0.ActionInterface;//项目中导入testInterface这个包public class ClassLoaderTest {public static void main(String args[]) {try {File file = new File("rtest.txt");BufferedReader in = new BufferedReader(new FileReader(file));String s = new String();while ((s = in.readLine()) != null) {//从rtest.txt中读取的url,根据url创建类装载器URL url = new URL(s);s = null;URLClassLoader myClassLoader = new URLClassLoader(new URL[] { url }, Thread.currentThread().getContextClassLoader());System.out.println(myClassLoader);Class myClass = myClassLoader.loadClass("uRLClassLoaderTest1.TestAction");ActionInterface action = (ActionInterface) myClass.newInstance();String str = action.action();System.out.println(str);//根据url1创建类装载器URL url1 = new URL("file:d:/test.jar");URLClassLoader myClassLoader1 = new URLClassLoader(new URL[] { url1 }, Thread.currentThread().getContextClassLoader());Class myClass1 = myClassLoader1.loadClass("uRLClassLoaderTest1.TestAction");ActionInterface action1 = (ActionInterface) myClass1.newInstance();String str1 = action1.action();System.out.println(str1);}} catch (Exception e) {e.printStackTrace();}}}
该代码先在该工程下建立一个文件rtext.txt,用来存储需要加载的jar的路径(路径为:file:d:/Test.jar),实现时,读取一条路径,加载一个

运行结果:

java.net.URLClassLoader@152b6651this ActionTest classthis ActionTest class
注意点:

前面打包的jar包的名字不能跟类名相同,比如不能起名为TestAction.jar和ActionInterface.jar

原创粉丝点击