Search code examples
javaclasspathutility

'which' command equivalent for finding resource(s) on Java classpath


Is there an equivalent of the UNIX 'which' command, i.e. for given resource(s), traverse all classpath components and tell me in which component(s) it is found? In particular when there are multiple occurrences on the classpath?

(Context: I just spent the best part of a day chasing a bug which boiled down to a very long classpath having a source directory with stale source preceding (and thus eclipsing) a compiled jar with compiled newer code.)

(Yes I know you can get this with 'java -verbose' but that produces tons of output.

Maybe 'java -verbose ... | grep SpecificResource' is the best way?)


Solution

  • I use a shell script for finding classes within a set of JARs. The relevant part is this:

    find /my/jars -name \*.jar | while read jar; do
        jar -tf "$jar" | fgrep --label="$jar" -l foo/bar/SomeClass.class
    done
    

    which lists all JARs in /my/jars containing a file foo/bar/SomeClass.class.

    Edit

    This one-liner from the comments also works:

    grep -rail --include=\*.jar foo/bar/SomeClass.class /my/jars