Search code examples
mavenmaven-2maven-3

Find jars containing a class file in Maven project


As the header says I wonder if there is such an opportunity in Maven to know the jar a class file gets loaded in a module. Just like dependency:tree, but I would like to see jars with a specific class file. Thanks!


Solution

  • As far as I know, there is no specific Maven plugin (3.0+) that will search dependencies for class declarations. However, I believe I understand your need and offer the following solutions:

    Finding duplicate declarations

    mvn dependency:analyze-duplicate -DcheckDuplicateClasses
    

    Find containing JAR within Eclipse

    Use CTRL+SHIFT+T to bring up the Open Type dialog. Entering part or the whole class name presents a list of containing JARs on the build classpath.

    Find containing JAR without IDE

    If more programatic control is required for checking on systems without an IDE, say a CI server, the following snippets can be used to list JAR files containing a specific class or even a specific name pattern. This approach uses Maven's dependency plugin to collect all dependencies in a temporary directory such that they may be easily searched.

    For Unix or Git Bash systems

    mvn clean dependency:copy-dependencies -DoutputDirectory=target/temp
    for j in target/temp/*.jar; do jar -tf $j | grep SomeClass && echo $j; done
    

    For Windows via cmd shell

    mvn clean dependency:copy-dependencies -DoutputDirectory=target/temp
    for /R %G in (target\temp\*.jar) do @jar -tf "%G" | find "SomeClass" && echo %G
    

    In either case, a matching entry's full package and class name will be displayed followed by the containing JAR file name. grep and find search parameters can be further refined to restrict matches as needed, such as SomeClass.class.

    Hope this helps.