Skip to content

Instantly share code, notes, and snippets.

@marcgeld
Created June 28, 2017 14:22
Show Gist options
  • Save marcgeld/58c18968741924d0c3382350956d5a87 to your computer and use it in GitHub Desktop.
Save marcgeld/58c18968741924d0c3382350956d5a87 to your computer and use it in GitHub Desktop.
Find in which jar file a class is located.
#!/usr/bin/env groovy
import groovy.io.FileType
import java.net.URL
import java.net.URLClassLoader
import java.nio.file.Paths
import java.security.CodeSource
import java.security.ProtectionDomain
def printelnerr = System.err.&println
def appName = this.getClass().getName()
def cli = new CliBuilder( usage:"${appName} --basedir <path_to_dir> --intersectdir <path_to_dir> " )
cli.with {
b( longOpt: 'basedir', 'path to directory with jars (Original)', args: 1, required: true )
c( longOpt: 'class', 'class to find', args: 1, required: true )
h( longOpt: 'help', 'Print help', required: false )
}
def options = cli.parse(args)
if (!options) {
return
}
if (options.h) {
cli.usage()
}
File baseDir = new File( options.b )
println "Basedir: ${baseDir}"
String className = new File( options.c )
className = className.replaceAll( /[\/\\\\]/ , ".")
// Base jars
baseDir.eachFileRecurse( FileType.FILES ) {
if( it.name.endsWith( '.jar' ) ) {
this.class.classLoader.rootLoader.addURL( it.toURI().toURL() )
}
}
Class clazz = Class.forName( className )
String clazzname = clazz.getName()
ClassLoader classLoader = clazz.getClassLoader()
ProtectionDomain protectionDomain = clazz.getProtectionDomain()
if ( protectionDomain != null ) {
//println "---> ${protectionDomain.getCodeSource()}"
CodeSource codeSource = protectionDomain.getCodeSource()
if ( codeSource != null ) {
URL location = codeSource.getLocation()
if ( location != null ) {
def path = Paths.get( location.toURI() )
println "Path to jar: '${path}'"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment