classloader and classpath

Some sample code to get class path , from which jar it is loaded:

private void printclasspath(Class cls) {

Class klass = cls;

URL location =

klass.getResource(‘/’ + klass.getName().replace(‘.’, ‘/’) +

“.class”);

System.out.println(” location is  ” + location.getFile());

}

private String getPath(Class cls) {

String cn = cls.getName();

String rn = cn.replace(‘.’, ‘/’) + “.class”;

String path = getClass().getClassLoader().getResource(rn).getPath();

int ix = path.indexOf(“!”);

if (ix >= 0) {

return path.substring(0, ix);

} else {

return path;

}

}

Advertisements