真正完成类的加载工作是通过调用 defineClass
来实现的;
而启动类的加载过程是通过调用 loadClass
来实现的;
就是类加载器分为加载和定义
protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] classData = getClassData(name); if (classData == null) { throw new ClassNotFoundException(); } else { return defineClass(name, classData, 0, classData.length); } }
private byte[] getClassData(String className) { String path = classNameToPath(className); try { InputStream ins = new FileInputStream(path); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int bytesNumRead = 0; while ((bytesNumRead = ins.read(buffer)) != -1) { baos.write(buffer, 0, bytesNumRead); } return baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; }
finClass方法中,先加载类全称字符串,返回byte数组,如果返回为空,即这个class文件不存在,则抛出classnotfountException;
如果这个文件存在,才开始定义这个类,此时,如果定义这个类失败,抛出NoClassDefFoundError ;
http://www.ibm.com/developerworks/cn/java/j-lo-classloader/