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 a Developer Evangelist at Oracle, focusing on microservices and AI. Mark has served as a Section Leader in Stanford's Code in Place program that has introduced tens of thousands of people to the joy of programming, he is a published author, a reviewer and contributor, a content creator and a lifelong learner. He enjoys traveling, meeting people and learning about foods and cultures of the world. Mark has worked at Oracle since 2006 and before that 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