Monday, August 25, 2008

[Bash] How to find a specific class in a jar file

When developing in java i sometimes wonder in what jar file a specific class belongs to, especially when facing NoClassFoundExceptions. :)

The following will search recursively for jar files starting with your current directory and then see if any of the jar files contain the class you are looking for.

Changing to use $CLASSPATH instead of location:
If you wish to use the script to find jar files in CLASSPATH instead of a location, change the line:

for i in `find . -name *.jar`

to:

for i in `echo $CLASSPATH | tr ':' '\n'`

You can use this as a script by copying the code below into a new file ".sh" and then run the script using "sh .sh" (requires the permissions to be set correctly using "chmod u+x .sh").


#!/bin/bash
echo "#############################################################"
echo "This script will look in all jar files recursivly for a "
echo "string, usually part of a classname. If the jar file contains "
echo "a file with the string the result will be output "
echo ""
echo ""
echo "Write the the class name (or part of) you are looking for "
echo "from current path location and recursive in all jar "
echo "files, example: java.lang.Object:"
echo ""

read -e CLASS
echo "Searching....."
echo ""

for i in `find . -name *.jar`
do
count=`jar -tf $i | grep -i $CLASS | wc -l`;
if [ $count -gt 0 ]; then
echo "---------- Found [$CLASS] in $i resulting in: ----------"
jar -tf $i | grep -i $CLASS
echo "---------------------------------------------------------"
fi
done;

echo "#############################################################"

No comments: