Find a jar file given the class name?

Jeffrey Knight picture Jeffrey Knight · Sep 30, 2009 · Viewed 56.2k times · Source

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, given "com.ibm.websphere.security.auth.WSSubject", how do you track down the appropriate jar file? ("google" is not the answer I'm looking for!)

The java docs do not give any hint of the jar file, and obviously the names of the jar files themselves offer no clue.

There must be a 'search local jars', or some sort of 'auto-resolve dependencies', trick in the java world. Ideally, I'm looking for the 'official' way to do this. I happen to be on a windows machine without cygwin.

Answer

Dan Dyer picture Dan Dyer · Sep 30, 2009

Save this as findclass.sh (or whatever), put it on your path and make it executable:

#!/bin/sh
find "$1" -name "*.jar" -exec sh -c 'jar -tf {}|grep -H --label {} '$2'' \;

The first parameter is the directory to search recursively and the second parameter is a regular expression (typically just a simple class name) to search for.

$ findclass.sh . WSSubject

The script relies on the -t option to the jar command (which lists the contents) and greps each table of contents, labelling any matches with the path of the JAR file in which it was found.