gpt4 book ai didi

java - 列出包子目录中的类

转载 作者:行者123 更新时间:2023-11-29 09:24:01 26 4
gpt4 key购买 nike

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

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

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

最佳答案

试试这个方法:

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;
}

关于java - 列出包子目录中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com