Reputation: 434
I've done a lot of searching and haven't found an answer to this question. Maybe this can't be done, but here's what I have
and I'd like
I can write my own child-first classloader to load Class1 by name when needed. This classloader will then search SomeLibrary-V1.jar first (before the parent classloader). However, the classloader for Class1 will not be set to my classloader since it will defer to a parent. This then means that my child classloader will not be used when Class1 tries to load a class which I want to come from SomeLibrary-V1.jar.
I think I need my classloader to be set as the classloader for Class1 class. I've looked at introspection to set the class loader to my classloader instance, but the classLoader field of the Class objects is not exposed. Another way might be to call definedClass() from my classloader, but then I can't really use the parents.
I've seen this but the answer there suggests writing a classloader but provides no details. I have provided some details here that call out additional questions/problems with that solution (I hope - and I didn't have the rep to add a comment).
I hope I'm just missing something here. Thanks for any help.
Upvotes: 3
Views: 1039
Reputation: 7792
While solution is possible any such solution will be a very brittle solution that will almost certainly will cause more problems then its worth. I'd say if it is at all possible avoid dependency on different versions of the same lib. May be look at the fact that you have such dependencies as a symptom of a problem and try to resolve the root cause.
Upvotes: 0
Reputation: 206776
Welcome to JAR Hell! This is not easily possible, because of the simplistic way that the classpath works in Java.
There are solutions, but no easy, quick fix. You could do all kinds of classloader tricks, as you've already found out, or use a module system such as OSGi.
Hopefully this will get better in the future, when Java 9 comes out, which will have a standard module system.
Upvotes: 3