Hints and tips on java

These are some helpful hints on various topics.

 

Locating where class is loaded from


When debugging Java application which contains of multiple multiple jars there are a number of cases where one gets lost in all the jars. Then is vital to know where a third party class is loaded from to know its exact version. To get the load location of StrangeClass, just evaluate the following expression in your runtime:

URL location = StrangeClass.class.getProtectionDomain().getCodeSource().getLocation();


Find the jar that contains given Java class

If you have a folder containing several jars and you want to quickly find which one contains given class, use the following script:

findjar.sh:

$dir=$1
$class=$2
if [ $# -ne 2 ]
then
  echo "Usage: `basename $0` <directory> <class>"
  exit 1
fi

for file in `find $dir -name *.jar`
do
unzip -t $file | grep $class && echo $file
done


Example: find the jar containing MyClass in the folder /my/jars/folder:

findjar.sh /my/jars/folder MyClass