I have two classes, Child1 and Child2, children of the class Parent. The class Parenthas a static member, and the two children classes have a static method run() using this static member. As I have to call Child1.run() and Child2.run() inside the same application, I want that each of the child class can access its own version of the static member of the parent class.
I know that it would be easier to put the static member of the parent class into the children class, but I can't modify the source code of the classes.
I read around that I shoud use two different classloaders, but I don't understand how. Can someone explain me how to use classloaders to achieve the result I mentioned, maybe with some example code?
Yes, what you ask is possible using two different ClassLoaders. You need to compile your classes (
Parent,Child1andChild2), but they should not be in the same classpath location as the class you're invoking them from (call that classMain).Instead, put them somewhere on your disk in a directory or put them in a jar file.
From that location, you can create multiple classloaders, and you can use the method
loadClassto load classes with it; and you can use reflection to invoke methods, like the methodrunon it.P.s. this is bad design for a general purpose application, but you didn't say you were making a general-purpose application. So I don't see any reason to dumb down SO by dissuading interesting questions that help explain how the JVM works.