Copy java object/class from one classloader to another classloader

佐手、 提交于 2020-01-12 15:51:12

问题


Hi is there a way to copy one class loaded context (atrributes etc) from one classloader (for instance a 'made' class Point) to another classloader?

Making clear, Example: I have an object Point on CL 1. Now running on another CL2, I want to creat this object in CL 3.

Some obj:

class Point {
int x;
int y;
public Point() {}
//getters and setters

Scenery:

... 
class CL2 {

// Running on CL 2
...
// Point obj from CL 1
Object point = gotFromCL1();

// Want to create the object on Cl2
Object pointCL2 = point.conversion();

But I can't use sun.reflection (not available) and serialization doesn't work since CL2 automatically "reconstruct" the object with CL 1.

One solution that I tought was do an "100%" java reflection rconstruct, basically getting the fields of object from CL2 and setting up on the new obj.

PS: It needs to run on Java 1.4.2 :'(


回答1:


See Transloader on how to copy classes between ClassLoaders if you need to do one of the following:

  • Clone almost any object graph from one ClassLoader to another

  • Take any object from a foreign ClassLoader and invoke any method on it without cloning it




回答2:


I believe he has the same Class (with the same name) but loaded and defined by two classloaders. The best thing to do is fix your system so the class is not loaded and twice.




回答3:


If the class is as simple as you describe it in your case, you could look at XMLEncoder. There are significant restrictions using it, but in simple cases it should get the job done.

EDIT: Given this limitation, I would say put the data in a Map and use that. You could even have the two classes store their state in a Map internally so that movement is pretty fluid.

If that can't work, then it looks like you are facing a roll your own XML/JSON or just plain CSV, depending on the complexity of the data.




回答4:


PowerMock classloading also provides something similar to TransLoader and it supports more advance use cases such as (some) reflection. You can easily execute a Runnable or Callable:

ClassloaderExecutor cle = new ClassloaderExecutor(classloader);
cle.execute(aRunnable); 
Object result = cle.execute(aCallable); // Result is cloned back to original CL

Have a look at the test case in the svn repo.

It's also available in Maven:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-classloading</artifactId>
    <version>1.4.6</version>
</dependency>  


来源:https://stackoverflow.com/questions/1735714/copy-java-object-class-from-one-classloader-to-another-classloader

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