How JVM works when two same jar be included in classpath

前端 未结 4 505
难免孤独
难免孤独 2021-01-01 20:27

It was a mistake of my co-worker: there was a jar named test.jar and he has fixed a bug of it. Then he re-compile the code and built a new jar named testnew.jar The proble

相关标签:
4条回答
  • 2021-01-01 21:03

    If there are duplicates, it reads the one which appears first in your classpath.

    Edit A classpath file in general looks something like this..

    <classpath>
            <classpathentry kind="lib" path="C:/Temp/test.jar"/>
            <classpathentry kind="lib" path="C:/Temp/testnew.jar"/>
        <classpathentry kind="output" path="build/classes"/>
    </classpath>
    

    If your classpath looks something like above, then your JVM will look into test.jar first, as it appears first in the classpath. If you want to test it on your own, try moving the classpathentry for testnew.jar above the entry of test.jar. You will see that it now refers testnew.jar instead of test.jar.

    Reference: FindingClasses

    0 讨论(0)
  • 2021-01-01 21:04

    Yeah, by default it uses classes from first jar. That's why you have to check library directory for duplicates. Happend so many times for me and my colleagues.

    0 讨论(0)
  • 2021-01-01 21:20

    JVM loads whatever specific JARs are on the classpath. Since java 6 there has also been a wildcard notation. Below are a couple of examples.

    java -cp ".:lib/example.jar" Main
    

    The above will only load classes found in the current directory and inside example.jar. Whereas the next example will use any jar to load classes from.

    java -cp ".:lib/*" Main
    

    I don't think the order for which jar in a directory is examined first to find a class is defined, just which ever order the OS gave when listing the files.

    It is likely your IDE (or whatever you're using to run your program) is using the latter notation to run your program. You could change it so that is uses the former, though it will break if you ever change the name of a jar or add new ones.

    0 讨论(0)
  • 2021-01-01 21:23

    As far as I can tell, it isn't defined.

    Java has a pluggable classloader system, and thus the only way to know what will happen is to look at the documentation of the ClassLoader class, probably in particular the ClassLoader#findClass method, which doesn't define a behavior for this, and to look at the relevant sections of the JLS and JVM specs, neither of which seem to specify a constraint on class loaders in this regard. Thus, unless the behavior is documented by the class loader being used by your web container, you can't know for certain which class will be loaded.

    The odds are that the first one found that matches the binary name of the class will be the one loaded, but there's a big difference between behavior we suppose to be the case, and behavior that is specified and/or documented.

    0 讨论(0)
提交回复
热议问题