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

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Which class file is loaded by the classloader ?

When using lots of third-party libraries, one problem might be that 2 of them package different versions of the same class, producing errors when method version conflicts happen.

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();

Add a jar file to Java load path at run time

Sometimes it is necessary to amend the class load path at run time. For example, dynamically adding jar files containing user-configurable JDBC data sources. The way this is done is truly monstrous -- the URL Path format was only revealed when a colleague looked into the Java library sources.

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 ();
        }
    }
}

Locate the jar in the classpath for a given class

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" ) ;
  }
}

Java - imgFromJar

// Inserire un immagine presente nel file jar dell'applicazione

try
		{
			icon = ImageIO.read(getClass().getResourceAsStream("imgs/icon.png")); // La preleva dal file jar
			setIconImage(icon);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS