Get a array of class files inside a package in Java [duplicate]
Asked Answered
P

2

10

I need a Class[] of all the class files contained in one of my source packages in Java.

I could n't find a standard method to do it in one shot. If someone can write a function to fetch that list would be really helpful.

Class[] myClasses = yourfunction();  // Return a list of class inside a source package in the currently working project in java
Proponent answered 6/6, 2012 at 8:14 Comment(2)
There is no standard way to enumerate all classes in a given package. In some cases it's not even possible (think of an URLClassLoader loading classes from a HTTP URL: there's no standardized way to enumerate files in a folder).Yah
See here for a manual workaround (it's not fool proof) - #177027Pvc
P
10

I am able to solve this problem using normal file I/O and search mechanism. You can check the answer as posted here.

private static List<Class> getClassesForPackage(Package pkg) {
    String pkgname = pkg.getName();

    List<Class> classes = new ArrayList<Class>();

    // Get a File object for the package
    File directory = null;
    String fullPath;
    String relPath = pkgname.replace('.', '/');

    //System.out.println("ClassDiscovery: Package: " + pkgname + " becomes Path:" + relPath);

    URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);

    //System.out.println("ClassDiscovery: Resource = " + resource);
    if (resource == null) {
        throw new RuntimeException("No resource for " + relPath);
    }
    fullPath = resource.getFile();
    //System.out.println("ClassDiscovery: FullPath = " + resource);

    try {
        directory = new File(resource.toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...", e);
    } catch (IllegalArgumentException e) {
        directory = null;
    }
    //System.out.println("ClassDiscovery: Directory = " + directory);

    if (directory != null && directory.exists()) {

        // Get the list of the files contained in the package
        String[] files = directory.list();
        for (int i = 0; i < files.length; i++) {

            // we are only interested in .class files
            if (files[i].endsWith(".class")) {

                // removes the .class extension
                String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);

                //System.out.println("ClassDiscovery: className = " + className);

                try {
                    classes.add(Class.forName(className));
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("ClassNotFoundException loading " + className);
                }
            }
        }
    } else {
        try {
            String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
            JarFile jarFile = new JarFile(jarPath);
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName();
                if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {

                    //System.out.println("ClassDiscovery: JarEntry: " + entryName);
                    String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");

                    //System.out.println("ClassDiscovery: className = " + className);
                    try {
                        classes.add(Class.forName(className));
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("ClassNotFoundException loading " + className);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
        }
    }
    return classes;
}
Proponent answered 12/6, 2012 at 10:5 Comment(3)
Soooo big, there must be an easier way...Logographic
@Logographic ya you can definitely reduce some lines of code from this code and also a better solution might exists, even I would like to see some shorter and more efficient code that does the same job.Proponent
Good answer...saved my lot's of timePassover
E
4

Did not try this on all VMs, but on a recent Oracle VM there is a shorter way:

Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("package/name/with/slashes/instead/dots");
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        System.out.println(url);
        System.out.println(new Scanner((InputStream) url.getContent()).useDelimiter("\\A").next());
    }

This will print out the names of the resources in the package, so you can use getResource(...) on them. The call url.getContent() will return an instance of sun.net.www.content.text.PlainTextInputStream which is a VM specific class.

Ease answered 10/5, 2015 at 7:59 Comment(1)
This doesn't work with jar under jdk 1.8. sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream throws NPE on attempt to read from it.Eleneeleni

© 2022 - 2024 — McMap. All rights reserved.