参考文献:http://blog.csdn.net/shixin1198/article/details/3733948
package uRLClassLoaderTest0; //定义接口ActionInterface public interface ActionInterface { public String action(); }完成后将其打包为testInterface.jar文件。
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方法,并将返回的值打印在控制台上。
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@152b6651 this ActionTest class this ActionTest class注意点:
前面打包的jar包的名字不能跟类名相同,比如不能起名为TestAction.jar和ActionInterface.jar