public static String getJar ( Class < ? > klass ) { Preconditions . checkNotNull ( klass , "klass" ) ; ClassLoader loader = klass . getClassLoader ( ) ; if ( loader != null ) { String class_file = klass . getName ( ) . replaceAll ( "\\." , "/" ) + ".class" ; try { for ( Enumeration < ? > itr = loader . getResources ( class_file ) ; itr . hasMoreElements ( ) ; ) { URL url = ( URL ) itr . nextElement ( ) ; String path = url . getPath ( ) ; if ( path . startsWith ( "file:" ) ) { path = path . substring ( "file:" . length ( ) ) ; } path = URLDecoder . decode ( path , "UTF-8" ) ; if ( "jar" . equals ( url . getProtocol ( ) ) ) { path = URLDecoder . decode ( path , "UTF-8" ) ; return path . replaceAll ( "!.*$" , "" ) ; } else if ( "file" . equals ( url . getProtocol ( ) ) ) { String klassName = klass . getName ( ) ; klassName = klassName . replace ( "." , "/" ) + ".class" ; path = path . substring ( 0 , path . length ( ) - klassName . length ( ) ) ; File baseDir = new File ( path ) ; File testDir = new File ( System . getProperty ( "test.build.dir" , "target/test-dir" ) ) ; testDir = testDir . getAbsoluteFile ( ) ; if ( ! testDir . exists ( ) ) { if ( ! testDir . mkdirs ( ) ) { throw new IOException ( "Unable to create directory :" + testDir . toString ( ) ) ; } } File tempJar = File . createTempFile ( TMP_HADOOP , "" , testDir ) ; tempJar = new File ( tempJar . getAbsolutePath ( ) + ".jar" ) ; createJar ( baseDir , tempJar ) ; return tempJar . getAbsolutePath ( ) ; } } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } return null ; }
Returns the full path to the Jar containing the class . It always return a JAR .