将字节数组加载到内存类加载器中

将字节数组加载到内存类加载器中,第1张

字节数组加载到内存类加载器中

我将在这里发布我过去做过的实现:

// mainString className = "tests.compiler.DynamicCompilationHelloWorldEtc";//...ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File classesDir = new File(tempDir);CustomClassLoader ccl = new CustomClassLoader(classLoader, classesDir);         if (ccl != null) {    Class clazz = ccl.loadClass(className);///...}

我的自定义ClassLoader:

package tests.classloader;import java.io.File;import java.io.FileInputStream;import java.nio.ByteBuffer;public class CustomClassLoader extends ClassLoader {    private File classesDir;    public CustomClassLoader(ClassLoader parent, File classesDir) {       super(parent);       this.classesDir = classesDir;    }    public Class findClass(String name) {       byte[] data = loadDataFromAny(name);       return defineClass(name, data, 0, data.length);    }    private byte[] loadDataFromAny(String name) {        name = name.replace('.', '/');        name = name + ".class";        byte[] ret = null;        try { File f = new File(classesDir.getAbsolutePath(), name); FileInputStream fis = new FileInputStream(f); ByteBuffer bb = ByteBuffer.allocate(4*1024);  byte[] buf = new byte[1024]; int readedBytes = -1; while ((readedBytes = fis.read(buf)) != -1) {     bb.put(buf, 0, readedBytes); } ret = bb.array();        }        catch (Exception e) { e.printStackTrace();        }        return ret;    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5490175.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存