We recently ran into a scenarium that we have two corporate dependencies and each one of them has a specific method with the same name, parameters and class, probably a copy-and-paste. Both dependencies are declared as direct dependency in my actual microservice.
Imagine something like:
-- Microservice
|-- Corporate dependency A
|-- com.enterprise.project.UtilityClass
| public static String someMethod(String someParameter)
|-- Corporate dependency B
|-- com.enterprise.project.UtilityClass
| public static String someMethod(String someParameter)
We noticed the problem because maven reported it in our build when we added the second dependency, we checked and even thought the output is the same, they have slightly different implementations. My question is, how does the JVM decides which one of this methods to use in runtime?
CodePudding user response:
It will depend upon which dependency is first on the classpath.
CodePudding user response:
In a "usual" situation, there is a -classpath property that you supply in a startup script of your application for example, and it contains a list of jars that will be "known". Now, if the UtilityClass resides in A.jar and B.jar, the order of appearance of these jars in the classpath will determine which class implementation will load:
Example:
java -classpath A.jar B.jar <whatever>
means that the UtilityClass from A.jar will be loaded, only because it comes first.
Now things become more complicated when you run things through maven, because it manages the -classpath by itself. Since maven 2.0.9 it uses order in pom.xml for classpath (see here for example).
If you have more "advanced" ways of loading the jars (like custom classloaders, then the answer can be different)...
Anyway, probably the best way is to come up with one dependency and exclude the other if its possible.
