Java:如何将存储为byte []的类加载到JVM中? [英] Java: How to load Class stored as byte[] into the JVM?

查看:127
本文介绍了Java:如何将存储为byte []的类加载到JVM中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人将整个.class文件序列化为byte [],并假设该类的名称已知(与byte []一起传递),那么如何转换byte [] - > Class - >然后加载它到JVM以便我以后可以通过调用Class.forName()来使用它?

If one has serialized the entire .class file into byte[], and assuming the name of the class is known (passed along with the byte[]), how do you convert byte[] -> Class -> then load it to the JVM so that I could later use it by calling the Class.forName()?

注意:
我'这样做是因为我将.class发送到另一台主机,并且主机的JVM不知道这个.class。

NOTE: I'm doing this because I sent the .class over to another host, and the host's JVM doesn't know about this .class.

推荐答案

<我实际上是在测试中使用这样的东西,将一组类定义作为byte []给一个ClassLoader:

I'm actually using something like this right now in a test to give a set of Class definitions as byte[] to a ClassLoader:

  public static class ByteClassLoader extends URLClassLoader {
    private final Map<String, byte[]> extraClassDefs;

    public ByteClassLoader(URL[] urls, ClassLoader parent, Map<String, byte[]> extraClassDefs) {
      super(urls, parent);
      this.extraClassDefs = new HashMap<String, byte[]>(extraClassDefs);
    }

    @Override
    protected Class<?> findClass(final String name) throws ClassNotFoundException {
      byte[] classBytes = this.extraClassDefs.remove(name);
      if (classBytes != null) {
        return defineClass(name, classBytes, 0, classBytes.length); 
      }
      return super.findClass(name);
    }

  }

这篇关于Java:如何将存储为byte []的类加载到JVM中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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