简单的从文件系统中加载类

package com.hong.classLoader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileClassLoader extends ClassLoader {
	private static int byteLength;

	public Class myLoadClass(String name) throws IOException {
		byte[] date = getBytesFromFile(name);
		// 参数name要包含包名,否则找不到
		return defineClass(this.getClass().getPackage().getName() + "." + name,
				date, 0, byteLength);
	}

	public byte[] getBytesFromFile(String name) throws IOException {
		FileInputStream fis = new FileInputStream(new File(
				"D:\\eclipse\\workspace\\MyProject\\bin\\com\\hong\\classLoader\\"
						+ name + ".class"));
		byte[] data = new byte[2048];
		int ch;
		while ((ch = fis.read(data)) != -1) {
			byteLength = ch;

		}
		return data;

	}
}

 继承ClassLoader,从文件系统中读取类的class文件,转换成byte流,调用defineClass 返回Class对象

 

main调用:

package com.hong.classLoader;

import java.io.IOException;

public class AppMain {
	public static void main(String[] args) throws IOException, Exception{
		FileClassLoader fileClassLoader = new FileClassLoader();
		
		Class fileClass=fileClassLoader.myLoadClass( "FileClassLoader");
		System.out.println(fileClass.newInstance().toString());
	}
}

 

你可能感兴趣的:(java,eclipse)