Java自定义类加载器问题 [英] Java custom class loader issue

查看:190
本文介绍了Java自定义类加载器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从客户端向服务器端发送一个Class对象。每次服务器需要加载客户端发送的Class对象而不是通过父委托模型重用它(在第一次迭代期间加载时)。

I'm sending a Class object from client to server side. Every time the server needs to load the Class object sent by the client instead of reusing it by parent delegation model (when it was loaded during the 1st iteration).

我正在尝试在服务器端使用自定义类加载器,其 loadClass(String)只需调用 findClass()而不是使用父层次结构进行检查。
为实现这一目标,我正在做以下事情:

I'm trying to use a custom class loader on the server side whose loadClass(String) simply calls findClass() instead of checking with parent hierarchy. To achieve this, I'm doing following:


  1. 通过读取客户端的.class文件生成byte []如下:




Class cl = com.example.XYZ.class;
String path = cl.getName().replace('.', '/') + ".class";
InputStream is = cl.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data = -1;
while((data=is.read())!=-1)
  bos.write(data);
byte[] classBinaryData = bos.toByteArray();


我发送 classBinaryData 到服务器端。


  1. 在服务器端,每次检索 byte [] ,通过匹配MD5校验和验证它是否与客户端相同,然后我创建自定义类加载器的新实例并传递字节数组,以便它可以用于从 findClass 中调用 defineClass

  1. On the server side, every time I retrieve the byte[], verify if it's the same as on client side by matching MD5 checksum, then I create a new instance of my custom class loader and pass the byte array so it could be used in calling defineClass from within findClass.

然而,我得到的任何一个错误(取决于我从.class创建byte []的方式)

However, I'm getting either of the errors (depending on the way I create byte[] out of .class)

不兼容的魔法值.....在班级档案中<未知>

com / example / XYZ(错误的名称:com / example / XYZ)来自 defineClass

我需要帮助才能弄清楚我的方法/代码中的错误。

I need help in figuring out the mistake in my approach/code.

推荐答案

你的byte []生成代码看起来很好。

Your byte[] generation code looks fine.

当我使用从代码生成的字节数组加载具有以下类加载器代码的类时,它能够成功加载类。

When I used the byte array generated form your code to load the class with following class loader code, it was able to load the class successfully.

class CustomClassLoader extends ClassLoader {

    public Class loadTheClass(String name, byte[] bytes) {

        return defineClass(name, bytes, 0, bytes.length);
    }
}

像这样使用这个类加载器

Using this classloader like this

CustomClassLoader ccl = new CustomClassLoader();
        Class cz = ccl.loadTheClass("com.example.XYZ", classBinaryData);
        Object o = cz.newInstance();




  1. 我认为你必须使用'。'在服务器端加载类时,而不是'/'

  2. 和确保在其他代码中不更改字节数组数据。

  1. I think you must use '.' instead of '/' in the name when you are loading the class at server side.
  2. And ensure that the byte array data is not changed in your other code.

这篇关于Java自定义类加载器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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