smci
smci

Reputation: 33938

'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?)

Upvotes: 1

Views: 471

Answers (3)

harto
harto

Reputation: 90493

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

Upvotes: 1

Miserable Variable
Miserable Variable

Reputation: 28752

See jwhich, I believe it does exactly what you are looking for. It is not difficult to roll your own but why do that when it is readily available?

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160191

Your best bet is to take your classpath and search each element for the class(es) in question.

In theory, classes are guaranteed to be loaded in classpath order. If your classpath has a wildcard element, however, it's no longer deterministic. So you'd need to check for those and just dump out the classpath elements that match the resource in question.

A short JRuby/Groovy script should do it if java -verbose doesn't give you all the info you need.

Upvotes: 0

Related Questions