Skip to content
Advertisement

Access static method from classes loaded by different ClassLoaders

I have two classes (A and B) which are loaded by different ClassLoaders. Furthermore, I have a third class, which providers static getter and setter methods. I hope following picture can clarify the situation:

enter image description here

The Data class looks as following:

JavaScript

In class A, I want to set the static value of Data and in B I want to retrieve this value. However, in B I always get the original value (which is "<fill in>"). I only have a basic understanding of ClassLoaders, so I’m not too sure what is going on under the hood. I thought that both ClassLoaders (clA and clB) will propagate to their parent ClassLoader and that I will get the same Data class in both. Can anyone give me some feedback on the behavior or point me in the direction to look at?

Update

When I print the hashCode() of both Data classes, I get different values for them (meaning obviously I don’t get access the same class). Is there and easy way to illustrate the ClassLoader hierarchy?

Advertisement

Answer

If your question is how to illustrate or visualize the classloader hierarchy for objects, then you can walk up each classes classloader in code. You mentioned that you are using groovy, so an example would look like:

JavaScript

I think you will find, in your code, the two Data objects are actually not loaded from the same classloader, which is why they have different static variables.

I put together a sample that has

  • Main (loaded from parent classloader)
  • DataObj with a static String (loaded also from parent classloader)
  • LoadA, which instantiates a copy of DataObj (loaded from child classloader A)
  • LoadB, which instantiates a copy of DataObj (loaded from child classloader B)

I see that while LoadA and LoadB have different classloaders, the DataObj and the static variable come from a common classloader.

Full code at: https://github.com/lucasmcgregor/groovy_classloader_test

The Main object in groovy:

JavaScript

The results are:

JavaScript

You see that LoadA and LoadB both have different classloaders, but they share a parent classloader.

The parent classloader loads the DataObj for both instances of the LoadA.dataObj and LoadB.dataObj.

LoadA.dataObj and LoadB.dataObj have different hashcodes.

However, LoadA.dataObj.data and LoadB.dataObj.data have the same hashcode, because this is the static object. They also have the same value. LoadB instantiates it’s dataObj last and sets the string to “Loaded By B”

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement