get Classes from package - Android java.lang.reflect

Android examples for java.lang.reflect:Package

Description

get Classes from package

Demo Code


//package com.java2s;

import java.io.File;

import java.util.ArrayList;

public class Main {
    public static Class[] getClasses(String pckgname)
            throws ClassNotFoundException {
        ArrayList classes = new ArrayList();
        // Get a File object for the package
        File directory = null;/*from  ww w . j a v  a 2  s .  c  om*/
        try {
            directory = new File(Thread.currentThread()
                    .getContextClassLoader()
                    .getResource('/' + pckgname.replace('.', '/'))
                    .getFile());
        } catch (NullPointerException x) {
            throw new ClassNotFoundException(pckgname
                    + " does not appear to be a valid package");
        }
        if (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
                    classes.add(Class.forName(pckgname + '.'
                            + files[i].substring(0, files[i].length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(pckgname
                    + " does not appear to be a valid package");
        }
        Class[] classesA = new Class[classes.size()];
        classes.toArray(classesA);
        return classesA;
    }
}

Related Tutorials