开发者

How to resolve a Class<> object received from network in the default classloader?

I am sending a Class<> object over the network.

Now, when I receive the object on the other side, I'd like to be able to 开发者_Go百科load it to the current class loader. The problem is that the only method that seems to do the job is protected (resolveClass(Class<?> c)). So, to use it, I'd have to extend the default classloader.

So, is there any easier way to do this?

Constraints: Unfortunately, I can't write to the server's disk, so the obvious solution to send the .class file instead of an object is not feasible.


When you use Class.forName(className) it resolves the class. You can also use ClassLoader.loadClass(classname) for a specific class loader.

The only way to load a class into the classloader is to have the byte code for that class. This only works if a class of this name has not been loaded before. You can force the class loader to load a class from byte code by calling ClassLoader.defineClass() using reflection.

You can get the byte code from the class loader

byte[] bytes = IOUtils.toByteArray(
     myClass.getClassLoader().getResourceAsInputStream(
         myClass.getName().replace('.','/')+".class"));

Note: to load a class, all it dependacies have to be loaded first. This is easy if all the dependencies are available, but get more complicated if you need to extract more classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜