Wednesday, September 17, 2008

Decompile and Javadoc a Jar with Matlock (Bash, Javadoc, and Jad) Without Ant or Maven

If you just want a unix command-line script to decompile and generate javadocs for a jar you found, use the matlock.sh script (named after the famous T.V. detective, Matlock):

matlock.sh:

#!/bin/bash

# matlock.sh
# Written by Gary S. Weaver 2008-09-17
# This decompiles and javadocs a jar.
# You must have javadoc ( part of the standard Java distribution ) and jad ( http://www.kpdus.com/jad.html ) in your PATH

set -e

if [ ! -f "$1" ]
then
  echo "not a valid, existing jar file: '$1'"
  echo ""
  echo "usage: matlock.sh <jar pathname>"
  exit
fi

if hash unzip 2>/dev/null; then
  unzip "$1" -d classes/
  if hash jad 2>/dev/null; then
    jad -o -r -sjava -dsrc "classes/**/*.class"
  else
    echo "put jad ( http://www.kpdus.com/jad.html ) in PATH to decompile into source"
  fi

  if hash javadoc 2>/dev/null; then
    javadoc -d apidocs -sourcepath src -subpackages edu:com:org
  else
    echo "put javadoc (part of the standard Java distribution) in PATH to produce javadocs"
  fi
else
  echo "put unzip in PATH to be able to decompress jar"
fi

Tips: Don't forget to chmod +x matlock.sh. If your top-level package is something other than edu, com, or org, add it to the list in the script. Remove the .sh from the filename for brevity.

If you're using windows, here is a batch file called matlock.bat to do the same thing, albeit with fewer checks and this also shows how you can javadoc default-package-level classes (how to javadoc classes in the default package from this email):

@echo off

rem matlock.bat
rem Written by Gary S. Weaver 2009-09-23
rem This decompiles and javadocs a jar.
rem You must have the following in your PATH:
rem javadoc ( part of the standard Java distribution ),
rem 7za.exe ( 7-zip command-line from http://www.7-zip.org/download.html ),
rem and jad ( http://www.kpdus.com/jad.html )
if (%1)==() goto help
if [%1] == [/?] goto help

if exist %1 goto step1
echo.
echo %1 does not exist  

:help
echo.
echo usage: matlock jarfile
goto end

:step1 
@echo on
7za.exe x -oclasses/ "%1"
jad -o -r -s java -d src "classes/**/*.class"
javadoc -d apidocs -sourcepath src -subpackages edu:com:org
javadoc -d apidocs-def -author src/*.java

:end

No comments: