Monday, May 10, 2010

How to Find a Class in any JAR Files

Two (in)famous exceptions in Java are NullPointerException and ClassNotFoundException. Those exceptions are actually quite easy to resolve. In most cases, the ClassNotFoundException occurs due to missing JAR file in a classpath.

I wrote a Groovy script to find a class in any JAR files so that you can easily find whether a particular file exists in any JAR file(s).

Enjoy :)

if (!validateArgs(this.args)) {
    System.exit(1)   
}

def dir = new File(this.args[0])
def entry = this.args[1]
dir.eachFileRecurse { jarFile ->
    if (jarFile.name.toLowerCase().endsWith('.jar')) {
        def jar = new java.util.jar.JarFile(jarFile)
        jar.entries().each { jarEntry ->
            if (jarEntry.name.toLowerCase().contains(entry.toLowerCase())) {
                println "${jarFile.absolutePath}: ${jarEntry.name}"
            }
        }
    }
}

def validateArgs(def args) {
    if (args.size() != 2) {
        printUsage()
        return false
    }
   
    def dir = new File(args[0])
    if (!dir.isDirectory()) {
        printUsage()
        return false
    }
    return true
}

def printUsage() {
    println "Usage: groovy ClassFinder.groovy [directory_to_search] [jar_entry]"
}

No comments:

Post a Comment