DZone 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

Mr B is a DZone employee and has posted 1 posts at DZone. You can read more from them at their website. View Full User Profile

Locate The Jar In The Classpath For A Given Class

02.07.2007
| 5824 views |
  • submit to reddit
        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

import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindJarForClass
{
  private FindJarForClass() {}

  public static String locate( Class c ) throws ClassNotFoundException
  {
    final URL location;
    final String classLocation = c.getName().replace('.', '/') + ".class";
    final ClassLoader loader = c.getClassLoader();
    if( loader == null )
    {
      location = ClassLoader.getSystemResource(classLocation);
    }
    else
    {
      location = loader.getResource(classLocation);
    }
    if( location != null ) 
    {
      Pattern p = Pattern.compile( "^.*:(.*)!.*$" ) ;
      Matcher m = p.matcher( location.toString() ) ;
      if( m.find() )
        return m.group( 1 ) ;
      else
        throw new ClassNotFoundException( "Cannot parse location of '" + location + "'.  Probably not loaded from a Jar" ) ;
    }
    else 
      throw new ClassNotFoundException( "Cannot find class '" + c.getName() + " using the classloader" ) ;
  }
}
    

Comments

Snippets Manager replied on Thu, 2007/02/15 - 4:31pm

What's wrong with Class.getProtectionDomain().getCodeSource().getLocation() ?