Finding a jar file which contains a Java class

By | December 4, 2010

Have you ever needed to find a jar file which contains a particular java class? If you’re answer is affirmative, please continue reading!

In this short article, I will share one way to do this task in the Unix-like world using sh, ksh or bash. There’re a lot of other ways to do this task so if you have a different one just leave a comment with the code and spread the knowledge!

Let’s start finding the jar files:

find <dir> -name '*.jar'

Now we need to print all jar files contents and find the java class, the first approach could be:

find <dir> -name '*.jar' | xargs -I @ jar -tvf @ | grep <java class>

We found the java class but we don’t know which jar file it belongs to so let’s try another way:

find <dir> -name '*.jar' | while read F; do (echo $F; jar -tvf $F | grep <java class>) done

Great! We can see which jar file is been inspected and when the java class is found it’s printed. Simple, isn’t it? This is just one line that shows the power of unix command shell!

Happy Hacking!


5 Comments

Jennifer on October 16, 2012 at 7:45 pm.

Thanks for this post! It saved me some time. Your solution says $FILE in one part though where it should just say $F.

Abner on October 16, 2012 at 11:49 pm.

Jennifer, thanks for the bug report :)

Hazem Saleh on October 24, 2012 at 11:30 pm.

Perfect and a very useful post. I will add to DZone to be seen by the technical community in order to make use of this technique.

Adam siemion on November 14, 2012 at 8:34 am.

A small improvement to your script that shows only the jars containing the specified class and ignores any errors:

find DIR -name ‘*.jar’ | while read F; do (jar -tvf $F 2>/dev/null | grep CLASS && echo $F) done

Srini on May 18, 2013 at 7:49 am.

Thanks you for the tip.

Leave Your Comment

Your email will not be published or shared. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>