Which class file is loaded by the classloader ?
Here is a simple way to know the exact location used by the classloader to get your class :
URL myClassURL = MyMysteryClass.class.getProtectionDomain().getCodeSource().getLocation();
11387 users tagging and storing useful source code snippets
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
URL myClassURL = MyMysteryClass.class.getProtectionDomain().getCodeSource().getLocation();
import java.net.URL; import java.io.IOException; import java.net.URLClassLoader; import java.net.MalformedURLException; public class JarFileLoader extends URLClassLoader { public JarFileLoader (URL[] urls) { super (urls); } public void addFile (String path) throws MalformedURLException { String urlPath = "jar:file://" + path + "!/"; addURL (new URL (urlPath)); } public static void main (String args []) { try { System.out.println ("First attempt..."); Class.forName ("org.gjt.mm.mysql.Driver"); } catch (Exception ex) { System.out.println ("Failed."); } try { URL urls [] = {}; JarFileLoader cl = new JarFileLoader (urls); cl.addFile ("/opt/mysql-connector-java-5.0.4/mysql-connector-java-5.0.4-bin.jar"); System.out.println ("Second attempt..."); cl.loadClass ("org.gjt.mm.mysql.Driver"); System.out.println ("Success!"); } catch (Exception ex) { System.out.println ("Failed."); ex.printStackTrace (); } } }
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" ) ; } }
try { icon = ImageIO.read(getClass().getResourceAsStream("imgs/icon.png")); // La preleva dal file jar setIconImage(icon); } catch(IOException e) { e.printStackTrace(); }