将字节数组加载到内存类加载器中 [英] Load a Byte Array into a Memory Class Loader

查看:184
本文介绍了将字节数组加载到内存类加载器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将一个字节数组加载到内存 URLClassLoader中?
字节数组是jar文件的解密字节(如下所示)!

I am wondering how I can load a byte array into a memory URLClassLoader? The byte array is the decrypted bytes of a jar file (as seen below)!

大多数内存类加载器都使用ClassLoader而不是URLClassLoader!
我需要它使用URLClassLoader。

Most of the memory class loaders are using ClassLoader and not URLClassLoader! I need it to be using URLClassLoader.

    byte[] fileB = Util.crypt.getFileBytes(inputFile);
    byte[] dec;
    dec = Util.crypt.decrypt(fileB, "16LENGTHLONGKEYX".getBytes());
    //Load bytes into memory and load a class here?

谢谢!

推荐答案

我将在此发布我过去做过的一个实现:

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

我的自定义ClassLoader: p>

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

这篇关于将字节数组加载到内存类加载器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆