Referencering a class loaded with different classloaders

J

jespersahner

Hi!

Suppose that two objects o1 and o2 are of the same type MyClass but are
loaded with different classloaders (o2 might be created after a reload
of MyClass after som bytecode-manipulation).

How do I cast/refer to (or create) new objects of each of the
"versions" of MyClass?

Regards,
Jesper
 
J

John C. Bollinger

Suppose that two objects o1 and o2 are of the same type MyClass but are
loaded with different classloaders (o2 might be created after a reload
of MyClass after som bytecode-manipulation).

Then they are not of the same class. Classes are scoped to the
ClassLoader that loaded them. If the bytecode of one is different from
the bytecode of the other then they are even less the same class.
How do I cast/refer to (or create) new objects of each of the
"versions" of MyClass?

You cannot successfully cast instances of one class to the other class.
They are different, largely unrelated classes. Since the two classes
have the same FQ name, there is no chance whatsoever that you can handle
instances of both "normally" in the same block of code at the same time.
You can choose a suitable superclass to use as the declared type of
these objects, though that superclass might be Object.

How you can instantiate these things depends a lot on your code. You
might find that you need to resort to Class.newInstance() or to using
one of the Class' Constructor objects. There are approaches that would
not require doing so (with use of ClassLoader tricks), but before you go
far along this path, you should be certain that you _really_ want to do
this. You can probably make it work, but it will cause you grief.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top