javajdeps

jdeps equivalent for Java 7


I need to analyse which classes are used (referenced) by the different .class files in a jar. I know that

jdeps -v example.jar

produces this output. Unfortunately, I need a solution that works if the user has only a JDK 1.7. How could this be achieved?


Solution

  • I've been able to obtain seemingly good results with javap -c and a regex filter.

    I used cygwin to obtain my results, but you should be able to do this in any environment, all you need is a tool to unzip, javap and a tool to execute regular expressions. In current Windows versions, powershell would provide those features.

    The following code will list the classes referenced by each class inside a jar file :

    mkdir workDir
    unzip yourJar.jar -d workDir
    shopt -s globstar
    for classFile in **/*.class; do
        echo "Classes used in $classFile :"
        javap -c "$classFile" | grep -Eo "([a-zA-Z0-9]+/)+[A-Z][a-zA-Z0-9]*" | sort -u
        echo
    done
    

    You said you wanted the classes referenced in a jar file, so assuming you don't want the detail of each class this should work :

    mkdir workDir
    unzip yourJar.jar -d workDir
    shopt -s globstar
    for classFile in **/*.class; do
        javap -c "$classFile" | grep -Eo "([a-zA-Z0-9]+/)+[A-Z][a-zA-Z0-9]*" 
    done | sort -u
    

    Note that this will miss classes which do not follow conventions, for example which are defined in the default package or whose name do not start by a capitalized letter.

    You will also retrieve classes which qualified name starts with an L : this represents arrays, and you might want to strip that L if you only care about the classname. There are other similar single-letters modifiers I can't remember.