środa, 18 czerwca 2014

Get all classes from JAR file - java

Because, sometimes it is not so easy to find a solution of the problem in the Internet I decided to put below a short function which can help in listing all classes from JAR file:

 public List<String> getAllClassesInJarFile(String fileName) {  
     JarFile jarFile;  
     ArrayList<String> list = new ArrayList<String>();  
     try {  
       jarFile = new JarFile(fileName);  
       Enumeration<JarEntry> enums = jarFile.entries();  
       while (enums.hasMoreElements()) {  
         JarEntry jarEntry = enums.nextElement();  
         String entryName = jarEntry.getName();  
         if (!jarEntry.isDirectory() && entryName.endsWith(".class")) {  
           StringBuilder className = new StringBuilder();  
           for (String part : jarEntry.getName().split("/")) {  
             if (className.length() != 0)  
               className.append(".");  
             className.append(part);  
             if (part.endsWith(".class"))  
               className.setLength(className.length()  
                   - ".class".length());  
           }  
           list.add(className.toString());  
         }  
       }  
       jarFile.close();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
     return list;  
   }  

This function can be connected with the other one, which checks if the class implement the specific interface:

 @SuppressWarnings({ "rawtypes", "unchecked" })  
   public List<String> getAllClassesImplementingInterface(String fileName,  
       Class interf) {  
     List<String> listOfClassesToCheck = getAllClassesInJarFile(fileName);  
     List<String> listOfClasses = new ArrayList<String>();  
     File file = new File(fileName);  
     URL fileURL;  
     URLClassLoader ucl = null;  
     try {  
       fileURL = file.toURI().toURL();  
       String jarURL = "jar:" + fileURL + "!/";  
       URL urls[] = { new URL(jarURL) };  
       ucl = new URLClassLoader(urls);  
     } catch (MalformedURLException e1) {  
       e1.printStackTrace();  
     }  
     for (String className : listOfClassesToCheck) {  
       Class<?> c;  
       try {  
         c = Class.forName(className, true, ucl);  
         if (interf.isAssignableFrom(c)) {  
           listOfClasses.add(c.getName());  
         }  
       } catch (ClassNotFoundException e) {  
         e.printStackTrace();  
       } catch (SecurityException e) {  
         e.printStackTrace();  
       }  
     }      
     return listOfClasses;  
   }