Java Class from Package getClasses(String pkg)

Here you can find the source of getClasses(String pkg)

Description

get Classes

License

Open Source License

Declaration

public static List<Class<?>> getClasses(String pkg) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * QMetry Automation Framework provides a powerful and versatile platform to
 * author//from   ww  w .  j  a  va2 s.com
 * Automated Test Cases in Behavior Driven, Keyword Driven or Code Driven
 * approach
 * Copyright 2016 Infostretch Corporation
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT
 * OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE
 * You should have received a copy of the GNU General Public License along with
 * this program in the name of LICENSE.txt in the root folder of the
 * distribution. If not, see https://opensource.org/licenses/gpl-3.0.html
 * See the NOTICE.TXT file in root folder of this source files distribution
 * for additional information regarding copyright ownership and licenses
 * of other open source software / files used by QMetry Automation Framework.
 * For any inquiry or need additional information, please contact
 * support-qaf@infostretch.com
 *******************************************************************************/

import java.io.File;
import java.io.IOException;

import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;

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

public class Main {
    private static final String CLASS_SUFIX = ".class";
    private static final String PROTOCOL_JAR = "jar";

    public static List<Class<?>> getClasses(String pkg) throws IOException {
        ClassLoader classLoader = Thread.currentThread()
                .getContextClassLoader();
        String path = pkg.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<Class<?>> classes = new ArrayList<Class<?>>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (resource.getProtocol().equalsIgnoreCase(PROTOCOL_JAR)) {
                try {
                    classes.addAll(getClassesFromJar(resource, pkg));
                } catch (IOException e) {
                    System.err.println("Unable to get classes from jar: "
                            + resource);
                }
            } else {
                try {
                    classes.addAll(getClasses(new File(resource.toURI()),
                            pkg));
                } catch (URISyntaxException e) {
                    // ignore it
                }
            }
        }
        return classes;
    }

    /**
     * Recursive method used to find all classes in a given directory and
     * subdirs.
     * 
     * @param directory
     *            The base directory
     * @param packageName
     *            The package name for classes found inside the base directory
     * @return The classes
     */
    private static List<Class<?>> getClasses(File directory,
            String packageName) {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                classes.addAll(getClasses(file,
                        packageName + "." + file.getName()));
            } else if (file.getName().endsWith(CLASS_SUFIX)) {
                String clsName = packageName
                        + '.'
                        + file.getName().substring(0,
                                file.getName().lastIndexOf("."));
                try {
                    classes.add(Class.forName(clsName));
                } catch (ClassNotFoundException e) {
                    // ignore it
                }
            }
        }
        return classes;
    }

    private static List<Class<?>> getClassesFromJar(URL jar, String pkg)
            throws IOException {
        List<Class<?>> classes = new ArrayList<Class<?>>();

        String jarFileName = URLDecoder.decode(jar.getFile(), "UTF-8");
        jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
        JarFile jf = new JarFile(jarFileName);
        Enumeration<JarEntry> jarEntries = jf.entries();

        while (jarEntries.hasMoreElements()) {
            String entryName = jarEntries.nextElement().getName()
                    .replace("/", ".");
            if (entryName.startsWith(pkg)
                    && entryName.endsWith(CLASS_SUFIX)) {
                entryName = entryName.substring(0,
                        entryName.lastIndexOf('.'));
                try {
                    classes.add(Class.forName(entryName));
                } catch (Throwable e) {
                    System.err.println("Unable to get class " + entryName
                            + " from jar " + jarFileName);
                }
            }
        }
        jf.close();

        return classes;
    }
}

Related

  1. getClasses(String packageName)
  2. getClasses(String packageName, Class inheritedType)
  3. getClasses(String pckgname)
  4. getClasses(String pckgname)
  5. getClasses(String pkg)
  6. getClassesForPackage(final String packageName)
  7. getClassesForPackage(Package pkg)
  8. getClassesForPackage(String packageName)
  9. getClassesForPackage(String packageName)