情境:
把項目中要用到的class檔案和jar放到D:\loader\terry\codex目錄下,如何讓項目通過代碼的方式實現載入和使用這些類呢。
方案:通過URLClassLoader構造D:\loader\terry\codex這個路徑下的類載入器,在通過Java反射機制進行執行個體化使用這些類
例子:
HelloWorld.java:
package terry.codex;/** * @編寫人: yh.zeng * @編寫時間:2017-12-3 下午2:29:57 * @檔案描述: todo */public class HelloWorld {public void sayHello(){System.out.println("HelloWorld。");}}
Test.java:
import java.io.File;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;/** * @編寫人: yh.zeng * @編寫時間:2017-12-3 下午2:26:59 * @檔案描述: todo */public class Test {public static void main(String args[]){ String fileUrlString = new File("D:\\loader").toURI().toString(); fileUrlString = fileUrlString.replaceAll("!/", "%21/");try {ClassLoader classLoader = new URLClassLoader(new URL[]{new URL(fileUrlString)});Class HelloWorldClazz = classLoader.loadClass("terry.codex.HelloWorld");Object helloWorld = HelloWorldClazz.newInstance();Method method = helloWorld.getClass().getMethod("sayHello", null);method.invoke(helloWorld, null);} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}
demo見:https://github.com/zengyh/CodeLibary/blob/master/src/clazzloader/UrlClassLoaderTest.java