Which java class file will be called if same class is packed in two jar files?

后端 未结 2 900
夕颜
夕颜 2020-12-28 19:52

I am working on opensource project. As of of now I don\'t have any customization in any class. So using all the jars files provided by opensource project. My question is if

相关标签:
2条回答
  • 2020-12-28 20:12

    Class loader is looking for the first place where needed resource is located. It means that if class with the same name and package appears in 2 jars the first found will be used. Which one is the first? According to the classpath: if for example class A appears in jars one.jar and two.jar and your command line is:

    java -cp one.jar;two.jar MyMain`

    the version from one.jar will be used. But if command line is

    java -cp two.jar;one.jar MyMain`

    the class from two.jar will be instantiated.

    0 讨论(0)
  • 2020-12-28 20:20

    In fact it depends on many factors:

    • If both jar files are in the same ClassLoader, for instance the Java classpath (-cp option), normally it should be the first file found in the jar list order.

    • If deployed in a JavaEE container, like in an EAR file or in WEB-INF/lib or a WAR file, there is no warranty the container will load the same class between two startups. In that context, the only thing sure is that WEB-INF/classes is searched before WEB-INF/lib

    • In a complex ClassLoader hierarchy, the default behavior is parent-first search but JavaEE implementations have introduced mechanisms like parent-last policy (WebSphere) or filtering thanks to deployment descriptors (WebLogic, JBoss/WildFly)

    An option may be to declare jar file dependencies in META-INF/MANIFEST.MF file thanks to the Class-Path attribute. It should enforce a loading order at the ClassLoader level, particularly when started with java -jar myapp.jar but it may depend on implementations in a JavaEE context.

    Remark: when using an OpenSource project, it may be fair to submit a change request and publish your changes or improvements so that the community takes benefits from it. Then your project may update to main stream without such a difficulty of wild patches in your ClassPath.

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