3/05/2008

How to find which jar file contains your class at 'runtime'

It's often happening when you want to get know where JVM takes some class from.
If this class potentially can be located in several folders/jars, you never know which one of them JVM uses.

There is a simple method allowing this:

/**
* Method returns code source of given class.
* This is URL of classpath folder, zip or jar file.
* If code source is unknown, returns null (for example, for classes java.io.*).
*
* @param clazz For example, java.sql.SQLException.class
* @return for example, "file:/C:/jdev10/jdev/mywork/classes/"
* or "file:/C:/works/projects/classes12.zip"
*/
public static String getCodeSource(Class clazz)
{
if (clazz == null ||
clazz.getProtectionDomain() == null ||
clazz.getProtectionDomain().getCodeSource() == null ||
clazz.getProtectionDomain().getCodeSource().getLocation() == null)

// This typically happens for system classloader
// (java.lang.* etc. classes)
return null;

return clazz.getProtectionDomain()
.getCodeSource().getLocation().toString();
}

1 комментарий:

Unknown комментирует...

how about just letting the JVM tell you

-XX:+TraceClassLoading