Finding which JAR contains a class – again!

I posted a few days ago about finding which JAR file contains a class file – something I often want to do.  My friend Chris Johnson promptly posted a better version here with caching – thanks Chris!

Chris said I inspired him to finish his script 🙂 and in return he has inspired me to improve it further.  As I often work with JAR files in a development environment, and often a lot of them, the search can take a while, so the caching is great.  But – those files can change over time, so I need the cache to be kept up to date.

Here is an updated version of Chris’ version that will update the cache if a JAR file is newer than the cache:

#!/bin/sh
TARGET="$1"

CACHEDIR=~/.jarfindcache

# prevent people from hitting Ctrl-C and breaking our cache
trap 'echo "Control-C disabled."' 2

if [ ! -d $CACHEDIR ]; then
    mkdir  $CACHEDIR
fi

for JARFILE in `find $PWD -name "*jar"`
do
  CACHEFILE=$CACHEDIR$JARFILE

  if [ ! -s $CACHEFILE ]; then
      mkdir -p `dirname $CACHEFILE`
      nohup jar tvf $JARFILE > $CACHEFILE
  # if the jar file has been updated, cache it again
  elif [ $JARFILE -nt $CACHEFILE ]; then
      nohup jar tvf $JARFILE > $CACHEFILE
  fi

  grep $TARGET $CACHEFILE > /dev/null
  if [ $? == 0 ]
  then
    echo "$TARGET is in $JARFILE"
  fi
done

P.S.  If you are running this on Ubuntu (or Debian), like me, you better make that first line a bit more explicit:

#!/bin/bash

Enjoy!

About Mark Nelson

Mark Nelson is an Architect in the Enterprise Cloud-Native Java Team at Oracle. Mark works mainly on making Java (traditional and microservices) easy to use in Kubernetes and the CNCF ecosystem. Before joining this team, Mark worked on Wercker, WebLogic and was a senior member of the A-Team since 2010, and worked in Sales Consulting at Oracle since 2006 and various roles at IBM since 1994.
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

1 Response to Finding which JAR contains a class – again!

  1. In my environment, “unzip -l” was much faster than “jar tvf” — thanks for the article though!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s