Sitemap

Java Class Conflicts

2 min readNov 29, 2022

--

So, what are we talking about here? When the Java runtime encounters a reference to a class, it searches for it’s definition in all jars in it’s classpath. In an ideal world, it will find exactly one such class and everything is well and good. Unfortunately, in most complex projects, that’s almost never the case 🤷‍♂

Root of all evil

The root cause of this issue is that Java defines it’s namespace in terms of packages and classes. The jar names are not taken into consideration at all. So, if two different jars provide the same class name with the same package name, then who gets picked up just depends on which jar is looked up first during classpath lookup

Identifying class conflict

Most of the times, you can figure out that you have a class conflict when you see error like java.lang.NoSuchMethodError: . This means that during compile time, the method existed, but during run-time, Java is not able to find the method. This mostly happens, when Java has loaded a different class with the same name (and package) and this class doesn’t have the desired method

Get Hashken Distro’s stories in your inbox

Join Medium for free to get updates from this writer.

The next step is to figure out which jars are providing the conflicting class. There are a few ways to go about this

  • In case you are using an IDE, all dependency jars should be present as part of the current project. Then a class search should show you the jars holding that class
  • Or you can use mvn dependency:copy-dependencies to copy over all dependency jars to a directory. Then it’s a matter of simply looping over all jars there and grepping their file contents

Possible Solutions

  • If you are using maven to produce a fat jar and you are seeing class conflicts in the produced fat jar, then moving the definition of your desired dependency to the top of your dependency list will ensure that maven picks the class from your desired dependency. When it sees the same class name in another dependency, maven will skip adding it to the output fat jar
  • If one of input dependencies (that holds the conflicting class defn.) is itself a fat jar being produced by you; then use maven shade plugin relocations to change the package name of the class.

--

--