遍历包中的所有java类
如何对java的一个package进行遍历,本片文章只介绍package中含有子package和jar文件的两种情况,其他情况不在本文章的考虑范围内。
1,含有子package的情况。
把package中的“.”换成“\”,然后把对包的遍历变成的目录的遍历,对目录中的文件判断后缀“.class”。
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 * 返回目录下的所有类名 3 * filePath: 要遍历的目录 4 * childPackage: 是否需要遍历子目录 5 * */ 6 private static List<String> getClassNameByFile(String filePath,boolean childPackage){ 7 List<String> myClassName = new ArrayList<String>(); 8 File file = new File(filePath); 9 File[] childFiles = file.listFiles(); 10 assert childFiles != null; 11 for(File childFile:childFiles){ 12 if(childFile.isDirectory()){ 13 myClassName.addAll(getClassNameByFile(childFile.getPath(),childPackage)); 14 }else{ 15 String childFilePath = childFile.getPath(); 16 if(childFilePath.endsWith(".class")){ 17 childFilePath = childFilePath.substring(childFilePath.lastIndexOf("\\")+1,childFilePath.lastIndexOf(".")); 18 myClassName.add(childFilePath); 19 } 20 } 21 } 22 return myClassName; 23 }
2,含有jar包的情况。
jar文件不能当普通的文件和目录对待,不过java为我们提供了JarFile类,我们可以通过JarFile的entries方法获得jar文件里面的内容,然后通过“.class”后缀进行判断。
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 * 返回jar中的所有子类的类名 3 * jarPath: 要遍历的jar包 4 * childPack: 是否需要对子包进行遍历。true,遍历;false,不遍历。 5 * */ 6 private static List<String> getClassNameByJar(String jarPath,boolean childPackage){ 7 List<String> myClassName = new ArrayList<String>(); 8 String[] jarInfo = jarPath.split("!"); 9 String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/")); 10 String packagePath = jarInfo[1].substring(1); 11 try{ 12 JarFile jarFile = new JarFile(jarFilePath); 13 Enumeration<JarEntry> entrys = jarFile.entries(); 14 while(entrys.hasMoreElements()){ 15 JarEntry jarEntry = entrys.nextElement(); 16 String entryName = jarEntry.getName(); 17 if(entryName.endsWith(".class")){ 18 if(entryName.startsWith(packagePath)){ 19 entryName=entryName.replace("/",".").substring(0,entryName.lastIndexOf(".")); 20 myClassName.add(entryName); 21 } 22 }else{ 23 int index = entryName.lastIndexOf("/"); 24 String myPackagePath; 25 if(index != -1){ 26 myPackagePath = entryName.substring(0,index); 27 }else { 28 myPackagePath = entryName; 29 } 30 if(myPackagePath.equals(packagePath)){ 31 entryName = entryName.replace("/",".").substring(0,entryName.lastIndexOf(".")); 32 myClassName.add(entryName); 33 } 34 } 35 } 36 }catch (Exception e){ 37 e.printStackTrace(); 38 } 39 return myClassName; 40 }