Search code examples
javajarclasspathclassloader

Which of the jar will be loaded in the JVM?


So suppose I have a jar with a different version in the ext folder and the other version is in the classpath. Which version the the jar will be loaded? As per my research, since the extension classloader runs before the classpath one so the library in the extension will be loaded. Or will it be overriding with the classpath one. And what will happen if the version are the same?


Solution

  • It will use the first class that it can find in the ClassLoader's hierarchy.

    So it will try to get the class from the next sequence of ClassLoaders:

    1. The Bootstrap ClassLoader composed of the Bootstrap classes (the rt.jar and several other important jar files in jre/lib).
    2. The Extension ClassLoader composed of the Extension classes (jar files in the extension folder jre/lib/ext).
    3. The System ClassLoader composed of the User classes (the classes located in the classpath defined).

    So as your class is not defined in #1 but in #2 and #3, the first class that it can find will be in #2, so it will get the version of the extension folder and simply ignore the one defined later in your classpath.

    See also How Classes are Found