Saturday, May 16, 2009

Getting jar name & location from loaded class

The following method with the classname passed as parameter will return the location of the jar from which the class is loaded.

import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

public static String getJarLocation(String className) {
try {
Class cls = Class.forName(className);
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation();
return loc.toString();
} catch (Exception e) {
e.printStackTrace();
}

return null;

}

Alternatively we can also add the following to the startup JVM paramteres , which will print all the classes loaded along with the jar names and its path.

-verbose:class

No comments:

 
Free Domain Names @ .co.nr!