列出包的子目录中的类

时间:2010-11-13 19:33:15

标签: java android package subdirectory

我不确定我是否在这里使用了正确的术语..但如果我的包名设置如下:

com.example.fungame
    -ClassA
    -ClassB
    -com.example.fungame.sprite
        -ClassC
        -ClassD

如何以编程方式获取Class[]子目录中所有类的数组(我猜是.sprite?)

1 个答案:

答案 0 :(得分:0)

试试这个方法:

public static Class[] getClasses(String pckgname) throws ClassNotFoundException {
    ArrayList classes=new ArrayList();
    File directory = null;
    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
                try {
                    Class cl = Class.forName(pckgname + '.' + files[i].substring(0, files[i].length() - 6));
                    classes.add(cl);
                } catch (ClassNotFoundException ex) {
                }
            }
        }   
    } else {
        throw new ClassNotFoundException(pckgname + " does not appear to be a valid package");
    }
Class[] classesA = new Class[classes.size()];
classes.toArray(classesA);
return classesA;
}