我不确定是否在这里使用正确的术语。但是,如果我的软件包名称是这样设置的:
com.example.fungame
-ClassA
-ClassB
-com.example.fungame.sprite
-ClassC
-ClassD
如何以编程方式获取
Class[]
子目录中所有类的数组(我猜是.sprite
)? 最佳答案
试试这个方法:
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;
}