Load a Byte Array into a Memory Class Loader

依然范特西╮ 提交于 2019-11-29 02:47:14

I will post here a implementation I had done in the past:

// main
String 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);
///...
}

My Custom 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;
    }
}

Have you looked at the NetworkClassLoader example in the ClassLoader javadocs:

http://docs.oracle.com/javase/6/docs/api/index.html?java/lang/ClassLoader.html

Using this as a base, you just need to implement the loadClassData method, which will pull the desired resource from decrypted jar bytes. You can wrap the decrypted bytes with a JarInputStream(new ByteArrayInputStream(dec)), then iterate through the jar entries until you find the resource / class you're interested in and then return the jar entry's byte array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!