Guest User

Find jars and classes

a guest
Feb 7th, 2014
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. package test;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.util.Enumeration;
  6. import java.util.jar.JarEntry;
  7. import java.util.jar.JarFile;
  8. import test.classtest.TestClass;
  9.  
  10. public class TestArea {
  11.     public static void main (String args[]) throws IOException {
  12.         ClassLoader loader = TestClass.class.getClassLoader();
  13.  
  14.         // find jar file of a class
  15.         // method 1
  16.         // ref http://stackoverflow.com/questions/1983839/determine-which-jar-file-a-class-is-from
  17.         String name = TestClass.class.getName().replaceAll("\\.", "/") + ".class";
  18.         System.out.println(loader.getResource(name));
  19.         // method 2
  20.         // ref http://stackoverflow.com/questions/4546632/how-to-determine-absolute-path-if-any-of-a-loaded-class
  21.         String path = TestClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
  22.         System.out.println(path);
  23.  
  24.         // find jars contain TestClass.class
  25.         // ref http://stackoverflow.com/questions/9630268/read-contents-of-jar-file-given-specific-path
  26.         File f = new File(path).getParentFile(); // WEB-INF/lib
  27.         for (File jar : f.listFiles()) {
  28.             String jarPath = jar.getAbsolutePath();
  29.             JarFile jarFile = new JarFile(jarPath);
  30.             for(Enumeration<JarEntry> em = jarFile.entries(); em.hasMoreElements();) {
  31.                 String s= em.nextElement().toString();
  32.                 if (s.endsWith("/TestClass.class")) {
  33.                     System.out.println(jarPath + " contains TestClass.class");
  34.                 }
  35.             }
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment