在硬盘上的字节码(.class文件)是如何或用什么加载到jvm里面的内存中的????

曹大哥 2014-05-16 09:25:27
有些人说是用类加载器,但类加载器不是对存放在jvm虚拟机内存中.calss文件的类进行加载的吗?如果是,那也就是.calss没被加载到jvm虚拟机内存里面之前,那是用什么方法将硬盘上的字节码(.class文件)是如何或用什么加载到jvm里面的内存中的????
...全文
584 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
曹大哥 2014-05-31
  • 打赏
  • 举报
回复
引用 2 楼 xuefeng0707 的回复:
果断是ClassLoader,自己实现的ClassLoader的findClass里可以读取class文件,把读到的byte[]传递给defineClass,这样就完成了加载class文件。 举个例子:
public class PathClassLoader extends ClassLoader {
	private File dir;
	
	public PathClassLoader(String path) {
		dir = new File(path);
	}
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		if(dir != null) {
			File clazzFile = new File(dir, name + ".class");
			if(clazzFile.exists()) {
				FileInputStream input = null;
				try {
					input = new FileInputStream(clazzFile);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len;
					while((len = input.read(buffer)) != -1) {
						baos.write(buffer, 0, len);
					}
					
					return defineClass(name, baos.toByteArray(), 0, baos.size());
				} catch(Exception e) {
					throw new ClassNotFoundException(name, e);
				} finally {
					if(input != null) {
						try {
							input.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return super.findClass(name);
	}
}
谢谢
xuefeng0707 2014-05-16
  • 打赏
  • 举报
回复
果断是ClassLoader,自己实现的ClassLoader的findClass里可以读取class文件,把读到的byte[]传递给defineClass,这样就完成了加载class文件。 举个例子:
public class PathClassLoader extends ClassLoader {
	private File dir;
	
	public PathClassLoader(String path) {
		dir = new File(path);
	}
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		if(dir != null) {
			File clazzFile = new File(dir, name + ".class");
			if(clazzFile.exists()) {
				FileInputStream input = null;
				try {
					input = new FileInputStream(clazzFile);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len;
					while((len = input.read(buffer)) != -1) {
						baos.write(buffer, 0, len);
					}
					
					return defineClass(name, baos.toByteArray(), 0, baos.size());
				} catch(Exception e) {
					throw new ClassNotFoundException(name, e);
				} finally {
					if(input != null) {
						try {
							input.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return super.findClass(name);
	}
}
vnvlyp 2014-05-16
  • 打赏
  • 举报
回复
没看过JVM实现帮顶 不过不应该就是JVM把文件读入内存,然后用ClassLoader来加载吗 或者应该ClassLoader本身就负责从文件加载到内存

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧