自訂類載入器-孫衛琴《Java物件導向編程》

來源:互聯網
上載者:User
package cn.edu.bnu.songjie.ch10.selfclassloader;import java.io.*;/** * 自訂的類載入器,只需要擴充ClassLoader,然後覆蓋它的findClass(Sring name)方法即可, * 該方法根據參數指定的類名,返回對應的Class對象的引用。 * @author songjie * */public class MyClassLoader extends ClassLoader{private String name;private String path = "d:\\";private final String fileType = ".class";public MyClassLoader(String name){this.name = name;}public MyClassLoader(ClassLoader parent, String name){super(parent);this.name = name;}public String toString(){return name;}public void setPath(String path){this.path = path;}public String getPath(){return path;}protected Class findClass(String name){byte[] data = loadClassData(name);return defineClass(name, data, 0, data.length);//此方法從ClassLoader繼承而來}/** * 把類的二級制資料讀入到記憶體 * @param name * @return */private byte[] loadClassData(String name){FileInputStream fis = null;byte[] data = null;ByteArrayOutputStream baos  = null;try{name = name.replaceAll("\\.", "\\\\");fis = new FileInputStream(new File(path+name+fileType));baos = new ByteArrayOutputStream();int ch = 0;while((ch = fis.read()) != -1){baos.write(ch);}data = baos.toByteArray();}catch(FileNotFoundException e1){System.out.println("檔案沒找到");}catch(IOException e2){System.out.println("檔案內容讀取異常");}finally{try{baos.close();fis.close();}catch(IOException e3){e3.printStackTrace();}}return data;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.