Skip to main content

Find the Source Jar of a Class file in Java

/**
*
* Gets the Source Jar File Location for the given Class,
* Useful to troubleshoot Class Related Exceptions/Errors.
* @param className
* @return
*/
public String getClassSourceJar(String className) {
 Class namedClass = null;
 String classSrcJarLocation = null;
try {
namedClass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException("The Requested Class is Not Found "+className);
}
CodeSource src = null;
if(namedClass!=null) {
src = namedClass.getProtectionDomain().getCodeSource();
 if(src!=null) {
 URL jar = src.getLocation();
 if(jar!=null) {
 classSrcJarLocation = jar.toString();
 }
 }
}
 return classSrcJarLocation;
}

Comments