自定義類加載器——加載任意指定目錄的class文件

public class MyClassLoader extends ClassLoader{
	String path;//自定義類加載器所負責的文件夾

	public MyClassLoader(String path) {
		super();
		this.path = path;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		//通過 文件輸入流 讀取 指定的class文件
		String file = path+"/"+name+".class";
		System.out.println(file);
		try {
			FileInputStream fis = new FileInputStream(file);
			//將讀取的class文件對應的 字節數據 寫入到內存中
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int i = 0;
			while ((i = fis.read())!=-1) {
				out.write(i);
			}
			fis.close();
			byte[] buf = out.toByteArray();//提取 寫到內存中的字節數據到數組
//	public byte[] toByteArray()創建一個新分配的 byte 數組。其大小是此輸出流的當前大小,並且緩衝區的有效內容已複製到該數組中。 
			return defineClass(buf, 0, buf.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.findClass(name);
	}
}

測試類

public class MyCLassLoaderTest {
	static Scanner in = new Scanner(System.in);

	public static void main(String[] args) throws Exception {
		System.out.println("需要加載的class文件所在文件夾的路徑:");
		String path = in.nextLine();// 需要加載的class文件的父路徑

		System.out.println("需要加載的class文件的文件名:");
		String name = in.nextLine();
		Class clazz = new MyClassLoader(path).loadClass(name);
		
		//執行加載的class文件的main方法
//		Method met = clazz.getMethod("main", String[].class);
//		System.out.println(met.toString());
//		met.invoke(null, (Object)new String[]{});
		
		// 通過自定義類加載器 加載任意目錄下的指定class文件
		Class clazz2 = new MyClassLoader(path).loadClass(name);
		System.out.println("\r\n--------------列出該class恩件中的所有構造方法==========");
		Constructor[] cons = clazz2.getConstructors();
		for (Constructor constructor : cons) {
			System.out.println(constructor.toString());
		}
		System.out.println("---------------列出該class恩件中的所有putong方法。。....。。");
		Method[] methods = clazz2.getMethods();
		for (Method method : methods) {
			System.out.println(method.toString());
		}
	}
}
//F:\java30\d24
//MyIEbyGUI


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章