This must be a very basic question for Java developers, but what is the best way to find the appropriate jar file given a class name?
For example, give
I use jarscan. It is an executable jar file that can recursively search an entire folder structure for jars that contain the class that you are looking for. It searches by class name, package name or regex.
To search all jars under the current directory and return the one(s) that contain class a.b.c.D do a:
find . -iname *.jar | while read JARF; do jar tvf $JARF | grep a/b/c/D.class && echo $JARF ; done
It will report all instances of class a.b.c.D (or classes with a similar suffix) and will only print the jars that contain it.
Typical output:
$ find . -iname *.jar | while read JARF; do jar tvf $JARF | grep Log.class && echo $JARF ; done
479 Fri Oct 10 18:19:40 PDT 2003 org/apache/commons/logging/Log.class
3714 Fri Oct 10 18:19:40 PDT 2003 org/apache/commons/logging/impl/Log4JCategoryLog.class
1963 Fri Oct 10 18:19:40 PDT 2003 org/apache/commons/logging/impl/NoOpLog.class
9065 Fri Oct 10 18:19:40 PDT 2003 org/apache/commons/logging/impl/SimpleLog.class
./WebContent/WEB-INF/lib/commons-logging.jar
Building up on Dan's excellent answer, the following script solves the problem of mangled output in case some of the jars are actually broken symlinks (while at the same time not skipping proper symlinks) It also searches in the current directory if no argument is provided.
#!/usr/bin/env bash
if [[ ($# -ne 1) && ($# -ne 2) ]]
then
echo "usage is $0 <grep RegEx to look for in contents of jar> [<top-of-folder-hierarchy> or, if missing, current dir]"
else
REG_EXP=$1
DIR=${2:-.}
if [ ! -d $DIR ]; then
echo "directory [$DIR] does not exist";
exit 1;
fi
find "$DIR" -name "*.jar" -exec sh -c '
(test -e {})
exitStatus=$?
if [ "$exitStatus" -eq 0 ]; then # this is done to avoid broken symlinks
jar -tf {}|grep -i -H --label {} '$REG_EXP'
fi
' \;
fi
Printing the list as I go so I can see what I'm checking. Mostly I'm looking in a lib/app directory, but you can substitute a locate for the find.
e.g.
for jar in $(find some_dir/lib -name "*.jar" );
do
echo -------------$jar-------------------
jar -tf $jar | grep TheNameOfTheClassImLookingFor
done
There is also this web site that seems to be usefull. http://www.findjar.com/
I have written a program for this: https://github.com/javalite/jar-explorer It will also decompile existing byte code to show you interfaces, methods, super classes, will show contents of other resources - text, images, html, etc.