Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Locate the jar in the classpath for a given class (See related posts)

This class has a single static method which when passed a class will return the location of the Jar file that loaded that class. Basically a refactoring of Laird Nelson's code from http://weblogs.java.net/blog/ljnelson/archive/2004/09/cheap_hack_i_re.html

   1  
   2  import java.net.URL;
   3  import java.util.regex.Matcher;
   4  import java.util.regex.Pattern;
   5  
   6  public class FindJarForClass
   7  {
   8    private FindJarForClass() {}
   9  
  10    public static String locate( Class c ) throws ClassNotFoundException
  11    {
  12      final URL location;
  13      final String classLocation = c.getName().replace('.', '/') + ".class";
  14      final ClassLoader loader = c.getClassLoader();
  15      if( loader == null )
  16      {
  17        location = ClassLoader.getSystemResource(classLocation);
  18      }
  19      else
  20      {
  21        location = loader.getResource(classLocation);
  22      }
  23      if( location != null ) 
  24      {
  25        Pattern p = Pattern.compile( "^.*:(.*)!.*$" ) ;
  26        Matcher m = p.matcher( location.toString() ) ;
  27        if( m.find() )
  28          return m.group( 1 ) ;
  29        else
  30          throw new ClassNotFoundException( "Cannot parse location of '" + location + "'.  Probably not loaded from a Jar" ) ;
  31      }
  32      else 
  33        throw new ClassNotFoundException( "Cannot find class '" + c.getName() + " using the classloader" ) ;
  34    }
  35  }

Comments on this post

gjoseph posts on Feb 15, 2007 at 15:43
What's wrong with Class.getProtectionDomain().getCodeSource().getLocation() ?

You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts