java自定義ClassLoader載入指定的class檔案
繼承ClassLoader並且重寫findClass方法就可以自定義一個類載入器,具體什麼是類載入器以及類載入器的載入過程與順序下次再說,下面給出一個小demo
首先定義一個類,比如MyTest,並且將其編譯成class檔案,然後放到一個指定的資料夾下面,其中資料夾的最後幾層就是它的包名,這裡我將這個編譯好的類放到 : /Users/allen/Desktop/cn/lijie/MyTest.class
package cn.lijie; public class MyTest { public void show() { System.out.println("show test!"); } }
自定義的類載入器:
public class MyClassLoader extends ClassLoader { @Override protected Class<?> findClass(String name) { String myPath = "file:///Users/allen/Desktop/" + name.replace(".","/") + ".class"; System.out.println(myPath); byte[] cLassBytes = null; Path path = null; try { path = Paths.get(new URI(myPath)); cLassBytes = Files.readAllBytes(path); } catch (IOException | URISyntaxException e) { e.printStackTrace(); } Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length); return clazz; } }
測試的主函式:
public class MainClass { public static void main(String[] args) throws ClassNotFoundException { MyClassLoader loader = new MyClassLoader(); Class<?> aClass = loader.findClass("cn.lijie.MyTest"); try { Object obj = aClass.newInstance(); Method method = aClass.getMethod("show"); method.invoke(obj); } catch (Exception e) { e.printStackTrace(); } } }
執行主函式,呼叫外部class的show方法:
繼承ClassLoader並且重寫findClass方法就可以自定義一個類載入器,具體什麼是類載入器以及類載入器的載入過程與順序下次再說,下面給出一個小demo
首先定義一個類,比如MyTest,並且將其編譯成class檔案,然後放到一個指定的資料夾下面,其中資料夾的最後幾層就是它的包名,這裡我將這個編譯好的類放到 : /Users/allen/Desktop/cn/lijie/MyTest.class
package cn.lijie;public class MyTest { public void show() { System.out.println("show test!"); }}123456自定義的類載入器:
public class MyClassLoader extends ClassLoader { @Override protected Class<?> findClass(String name) { String myPath = "file:///Users/allen/Desktop/" + name.replace(".","/") + ".class"; System.out.println(myPath); byte[] cLassBytes = null; Path path = null; try { path = Paths.get(new URI(myPath)); cLassBytes = Files.readAllBytes(path); } catch (IOException | URISyntaxException e) { e.printStackTrace(); } Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length); return clazz; }}1234567891011121314151617測試的主函式:
public class MainClass { public static void main(String[] args) throws ClassNotFoundException { MyClassLoader loader = new MyClassLoader(); Class<?> aClass = loader.findClass("cn.lijie.MyTest"); try { Object obj = aClass.newInstance(); Method method = aClass.getMethod("show"); method.invoke(obj); } catch (Exception e) { e.printStackTrace(); } }}12345678910111213執行主函式,呼叫外部class的show方法:
————————————————版權宣告:本文為CSDN博主「lijie_cq」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。原文連結:https://blog.csdn.net/qq_20641565/java/article/details/78744677