Does anyone have code to detect duplicate JARs in the classpath?
Background: When there are two versions of the same JAR in the classpath, really strange things can happen. This can even happen when using tools like Maven: Change a dependency and build the WAR without cleaning first. Since target/webapp/WEB-INF/lib
wasn't cleaned, the dependency will be in there twice.
Is there a safety-net for this?
To check our CLASSPATH on Windows we can open a command prompt and type echo %CLASSPATH%. To check it on a Mac you need to open a terminal and type echo $CLASSPATH.
The, the idea is to use find on the root of your classpath to locate all jars, then runs findclass.sh on all found jars to look for a match. It doesn't handle multi-directories, but if you carefully choose the root you can get it to work.
Another way of viewing the classpath is to run this Java code: String classpath = System. getProperty("java. class.
JBoss Tattletale might help you with this.
It's a free tool which scans the JAR files used by your project and gives you a report about them.
Amongst its feature are:
There is a Maven plugin to do just that: maven-duplicate-finder-plugin
[EDIT] If you want to do it in unit tests yourself, use
getClass().getClassLoader().getResources( "com/pany/package/Java.class" )
If this returns more than one URL
, you have duplicates on the classpath.
The drawback is that this only works for cases where you had conflicts in the past. On the positive side, it's just a few lines of code (or one line when you write a helper method) and it works on your build server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With