加载字节码到内存的组件是啥

果断是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);
    }

 

posted @ 2019-03-04 10:58  隔壁w王叔叔  阅读(168)  评论(0)    收藏  举报