Java Class from Package getClasses(String packageName)

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

Description

Locates all classes in given package

License

Apache License

Parameter

Parameter Description
packageName a parameter

Exception

Parameter Description
ClassNotFoundException an exception
IOException an exception

Return

array of the classes

Declaration

public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException 

Method Source Code


//package com.java2s;
/*/*ww w  .  ja va 2  s . c om*/
* Copyright (c) 2010 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*           http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

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

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

public class Main {
    /**
     * Locates all classes in given package
     *
     * @param  packageName
     * @return array of the classes
     * @throws ClassNotFoundException
     * @throws IOException
     */
    public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException {
        String path = packageName.replace('.', '/');
        List<URL> dirs = getDirectories(path);
        ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
        ClassLoader loader = URLClassLoader.newInstance(dirs.toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader());

        for (URL directory : dirs) {
            String resource = directory.getPath().replace("/" + path + "/", "");
            if (resource.endsWith(".jar")) {
                classes.addAll(getClassNamesInJarPackage(loader, resource, packageName));
            } else {
                classes.addAll(getClassNamesInPackage(new File(directory.getFile()), packageName));
            }
        }
        return classes;
    }

    /**
     * Locate all directories in given package
     *
     * @param path
     * @return Map<URL, File>
     * @throws IOException
     */
    public static List<URL> getDirectories(String path) throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        Enumeration<URL> resources = classLoader.getResources(path);
        List<URL> dirs = new ArrayList<URL>();
        while (resources.hasMoreElements()) {
            dirs.add(resources.nextElement());
        }
        return dirs;
    }

    /**
     * Locates all classes in given jar package
     *
     * @param  jarName
     * @param  url
     * @param  packageName
     * @return List of classes
     * @throws MalformedURLException
     */
    static List<Class<?>> getClassNamesInJarPackage(ClassLoader loader, String jarName, String packageName)
            throws MalformedURLException {
        ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

        packageName = packageName.replaceAll("\\.", "/");

        JarInputStream jarFileInputStream = null;
        try {
            jarFileInputStream = new JarInputStream(new FileInputStream(jarName));
            JarEntry jarEntry;
            while (true) {
                jarEntry = jarFileInputStream.getNextJarEntry();
                if (jarEntry == null)
                    break;
                if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) {
                    classes.add(loader.loadClass(jarEntry.getName().replaceAll("/", "\\.").replace(".class", "")));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (jarFileInputStream != null) {
                    jarFileInputStream.close();
                }
            } catch (IOException e) {
                //ignore
            }
        }
        return classes;
    }

    /**
     * Locates all classes in given package
     *
     * @param  directory
     * @param  packageName
     * @return List of classes
     * @throws ClassNotFoundException
     */
    private static List<Class<?>> getClassNamesInPackage(File directory, String packageName)
            throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(getClassNamesInPackage(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class
                        .forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }
}

Related

  1. getClasses(String packageName)
  2. getClasses(String packageName)
  3. getClasses(String packageName)
  4. getClasses(String packageName)