import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List;
public abstract class PackageScan {
public static ListgetClassName(String packageName) { ListclassNames = new ArrayList(); ClassLoader loader = Thread.currentThread().getContextClassLoader();
try { String resourceName = packageName.replaceAll("\\.", "/"); URL url = loader.getResource(resourceName); File urlFile = new File(url.toURI()); File[] files = urlFile.listFiles(); for (File f : files) getClassName(packageName, f, classNames); } catch (URISyntaxException e) { e.printStackTrace(); } return classNames; }
private static void getClassName(String packageName, File packageFile,Listlist) { if (packageFile.isFile()) { list.add(packageName + "."+ packageFile.getName().replace(".class", "")); } else { File[] files = packageFile.listFiles(); String tmPackageName = packageName + "." + packageFile.getName(); for (File f : files) { getClassName(tmPackageName, f, list); } } } }
测试类:
import com.mvc.auth.common.util.PackageScan;
public class Test {
public static void main(String[] args) {
Listlist = PackageScan.getClassName("com.mvc.auth");
for (String s : list) {
System.out.println(s);
}
}
}