Java Class from Package getClassesInPackage(String targetPackage)

Here you can find the source of getClassesInPackage(String targetPackage)

Description

Returns an array of classes within a target package

License

Open Source License

Parameter

Parameter Description
targetPackage target package

Return

an array of classes within a target package

Declaration

public static Class[] getClassesInPackage(String targetPackage) 

Method Source Code


//package com.java2s;
/*/*from   w w  w . j  av  a  2 s . c o  m*/
 * ReflectionHelper
 *
 * 8/23/13
 *
 * Copyright (c) 2013, Marcus Stojcevich
 * All rights reserved.
 * See the included LICENSE file
 */

import java.io.File;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**
     * Returns an array of classes within a target package
     * @param targetPackage target package
     * @return an array of classes within a target package
     */
    public static Class[] getClassesInPackage(String targetPackage) {
        List<Class> classList = new ArrayList<Class>();
        URL packageResource = Thread.currentThread().getContextClassLoader()
                .getResource(targetPackage.replace(".", "/").trim());
        if (packageResource == null) {
            System.out.println("Could not create resource for package " + targetPackage);
            return null;
        }
        File packageDirectory = new File(packageResource.getFile());
        for (String filename : packageDirectory.list()) {
            if (filename.endsWith(".class")) {
                String className = targetPackage + "." + filename;
                try {
                    classList.add(Class.forName(className.replace(".class", "")));
                } catch (ClassNotFoundException e) {
                    System.out.println("Error attempting to load classes from " + targetPackage);
                    e.printStackTrace();
                }
            }
        }
        return classList.toArray(new Class[classList.size()]);
    }
}

Related

  1. getClassesForPackage(String pckgname)
  2. getClassesInPackage(String packageName)
  3. getClassesInPackage(String packageName)
  4. getClassesInPackage(String packageName)
  5. getClassesInPackage(String pckgname)
  6. getClassNameByPackage(String packageName)
  7. getClassNamesByPkg(String pkg)
  8. getClassNamesForPackage(final Package p)
  9. getClassNamesFromPackage(String packageName)