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 }
You need to create an account or log in to post comments to this site.