2

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

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

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

4

1 回答 1

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;
}
于 2010-11-13T20:13:01.970 回答