Java/Namespaces in Java to resolve jar clashes

Advertisement

Expert: Artemus Harper - 3/24/2014

QuestionIs there any namespace kind of concept in JAVA where we can tell our code to pick up a certain jar package structure from a specified jar file only. I actually intend to tell the program that kindly lift jar and class files from "XYZ.jar", the jar version i want to work with, so that jar clash possibility in annuled.

Is there any way to do this?

Thanks..

AnswerYes, you can use the URLClassLoader to load an additional set of classes from a set of jars, folder locations, or http addresses. From there you can use the loadClass method to get a class object, and the newInstance() method in Class to create a new instance of the class.

Note that if you want to load multiple classes with the same name they must both be loaded in different URLClassLoaders and cannot be in your current classpath. If the class you are using is in your current classpath then it will be used regardless of whether it exists in the jar you want. You may need to create a simple set of loader classes on their own classpath to load both version separably.