Java Jar Usage findClassesByJar(String packageName, JarFile jar, final boolean recursive, Set> classes)

Here you can find the source of findClassesByJar(String packageName, JarFile jar, final boolean recursive, Set> classes)

Description

find Classes By Jar

License

LGPL

Declaration

public static void findClassesByJar(String packageName, JarFile jar, final boolean recursive,
            Set<Class<?>> classes) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.util.Enumeration;

import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Main {
    public static void findClassesByJar(String packageName, JarFile jar, final boolean recursive,
            Set<Class<?>> classes) {
        String packageDirName = packageName.replace('.', '/');

        Enumeration<JarEntry> jarEntries = jar.entries();
        JarEntry jarEntry;/*from   ww w.  j  av a2 s .  c om*/
        String name, className;
        Class<?> claze;
        while (jarEntries.hasMoreElements()) {
            jarEntry = jarEntries.nextElement();
            name = jarEntry.getName();
            if (name.charAt(0) == '/') {
                name = name.substring(1);
            }
            if (name.startsWith(packageDirName)) {
                int index = name.lastIndexOf('/');
                if (index > -1) {// it is a package that end with /
                    packageName = name.substring(0, index).replace('/', '.');
                }
                if ((index > -1) || recursive) {
                    if (name.endsWith(".class") && !jarEntry.isDirectory()) {
                        // remove ".class", retrieve the real class name
                        className = name.substring(packageName.length() + 1, name.length() - 6);
                        claze = getClaze(packageName, className);
                        if (claze != null) {
                            classes.add(claze);
                        }
                    }
                }
            }
        }
    }

    public static Class<?> getClaze(String packageName, String className) {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. checkJarValidity(String path)
  2. containsClass(JarFile jarFile, String agentRunnerClassName)
  3. containsClass(JarFile jarFile, String classFilePath)
  4. convertAttributes(Attributes attributes)
  5. createPacker()
  6. getAttribute(String name, String value)
  7. getClassNameByJar(String jarPath, boolean childPackage)
  8. getEntriesName(String jarFileName)
  9. getFileNamesWithSuffixForJarFile(JarFile jar, String suffix)