Java Class from Package getClassNamesFromPackage(String packageName)

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

Description

get Class Names From Package

License

Apache License

Declaration

public static ArrayList<String> getClassNamesFromPackage(String packageName) throws IOException 

Method Source Code


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

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import java.util.Enumeration;

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

public class Main {
    public static ArrayList<String> getClassNamesFromPackage(String packageName) throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ArrayList<String> names = new ArrayList<String>();
        packageName = packageName.replace(".", File.separator) + File.separator;
        URL packageURL = classLoader.getResource(packageName);
        if (packageURL.getProtocol().equals("jar")) {
            String jarFileName;/*from w  ww  .j a va 2  s  .  c  o  m*/
            JarFile jf;
            Enumeration<JarEntry> jarEntries;
            String entryName;
            // build jar file name         
            jarFileName = packageURL.getFile();
            jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
            System.out.println(">" + jarFileName);
            jf = new JarFile(jarFileName);
            jarEntries = jf.entries();
            while (jarEntries.hasMoreElements()) {
                entryName = jarEntries.nextElement().getName();
                if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {
                    entryName = entryName.substring(packageName.length(), entryName.lastIndexOf('.'));
                    names.add(entryName);
                }
            }
        } else {
            File folder = new File(packageURL.getFile());
            File[] contenuti = folder.listFiles();
            String entryName;
            for (File actual : contenuti) {
                entryName = actual.getName();
                entryName = entryName.substring(0, entryName.lastIndexOf('.'));
                names.add(entryName);
            }
        }
        return names;
    }
}

Related

  1. getClassNameByPackage(String packageName)
  2. getClassNamesByPkg(String pkg)
  3. getClassNamesForPackage(final Package p)
  4. getClassNamesFromPackage(String packageName)
  5. getClassNamesFromPackage(String packageName)
  6. getClassNamesPackage(String pckgname)