如何反射一个包下的所有类到一个List<Class<
private static List<Class> getClassesByPackageName(String packageName)
throws IOException, ClassNotFoundException {
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<Class>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
private static List<Class> findClasses(File directory, String packageName)
throws ClassNotFoundException {
List<Class> classes = new ArrayList<Class>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
// 递归查找文件夹【即对应的包】下面的所有文件
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + '.'
+ file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName
+ "."
+ file.getName().substring(0,
file.getName().length() - 6)));
}
}
return classes;
}
public static void main(String[] args) {
try {
List<Class> list=getClassesByPackageName("com.test");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这样是获取指定包下的所有类,你拿去用下