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

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());
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值