ClassUtil { public static String findContainingJar(Class<?> clazz) { ClassLoader loader = clazz.getClassLoader(); String classFile = clazz.getName().replaceAll("\\.", "/") + ".class"; try { for(final Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) { final URL url = itr.nextElement(); if ("jar".equals(url.getProtocol())) { String toReturn = url.getPath(); if (toReturn.startsWith("file:")) { toReturn = toReturn.substring("file:".length()); } toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }  static String findContainingJar(Class<?> clazz);  }
@Test(timeout=1000) public void testFindContainingJar() { String containingJar = ClassUtil.findContainingJar(Logger.class); Assert.assertNotNull("Containing jar not found for Logger", containingJar); File jarFile = new File(containingJar); Assert.assertTrue("Containing jar does not exist on file system ", jarFile.exists()); Assert.assertTrue("Incorrect jar file " + containingJar, jarFile.getName().matches("log4j.*[.]jar")); }