1. 程式人生 > >Java遍歷包中所有類

Java遍歷包中所有類

  1. package com.itkt.mtravel.hotel.util;  
  2. import java.io.File;  
  3. import java.net.URL;  
  4. import java.net.URLClassLoader;  
  5. import java.util.ArrayList;  
  6. import java.util.Enumeration;  
  7. import java.util.List;  
  8. import java.util.jar.JarEntry;  
  9. import java.util.jar.JarFile;  
  10. publicclass PackageUtil {  
  11.     public
    staticvoid main(String[] args) throws Exception {  
  12.         String packageName = "com.wang.vo.request.hotel";  
  13.         // List<String> classNames = getClassName(packageName);
  14.         List<String> classNames = getClassName(packageName, false);  
  15.         if (classNames != null) {  
  16.             for
     (String className : classNames) {  
  17.                 System.out.println(className);  
  18.             }  
  19.         }  
  20.     }  
  21.     /** 
  22.      * 獲取某包下(包括該包的所有子包)所有類 
  23.      * @param packageName 包名 
  24.      * @return 類的完整名稱 
  25.      */
  26.     publicstatic List<String> getClassName(String packageName) {  
  27.         return
     getClassName(packageName, true);  
  28.     }  
  29.     /** 
  30.      * 獲取某包下所有類 
  31.      * @param packageName 包名 
  32.      * @param childPackage 是否遍歷子包 
  33.      * @return 類的完整名稱 
  34.      */
  35.     publicstatic List<String> getClassName(String packageName, boolean childPackage) {  
  36.         List<String> fileNames = null;  
  37.         ClassLoader loader = Thread.currentThread().getContextClassLoader();  
  38.         String packagePath = packageName.replace(".""/");  
  39.         URL url = loader.getResource(packagePath);  
  40.         if (url != null) {  
  41.             String type = url.getProtocol();  
  42.             if (type.equals("file")) {  
  43.                 fileNames = getClassNameByFile(url.getPath(), null, childPackage);  
  44.             } elseif (type.equals("jar")) {  
  45.                 fileNames = getClassNameByJar(url.getPath(), childPackage);  
  46.             }  
  47.         } else {  
  48.             fileNames = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage);  
  49.         }  
  50.         return fileNames;  
  51.     }  
  52.     /** 
  53.      * 從專案檔案獲取某包下所有類 
  54.      * @param filePath 檔案路徑 
  55.      * @param className 類名集合 
  56.      * @param childPackage 是否遍歷子包 
  57.      * @return 類的完整名稱 
  58.      */
  59.     privatestatic List<String> getClassNameByFile(String filePath, List<String> className, boolean childPackage) {  
  60.         List<String> myClassName = new ArrayList<String>();  
  61.         File file = new File(filePath);  
  62.         File[] childFiles = file.listFiles();  
  63.         for (File childFile : childFiles) {  
  64.             if (childFile.isDirectory()) {  
  65.                 if (childPackage) {  
  66.                     myClassName.addAll(getClassNameByFile(childFile.getPath(), myClassName, childPackage));  
  67.                 }  
  68.             } else {  
  69.                 String childFilePath = childFile.getPath();  
  70.                 if (childFilePath.endsWith(".class")) {  
  71.                     childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf("."));  
  72.                     childFilePath = childFilePath.replace("\\", ".");  
  73.                     myClassName.add(childFilePath);  
  74.                 }  
  75.             }  
  76.         }  
  77.         return myClassName;  
  78.     }  
  79.     /** 
  80.      * 從jar獲取某包下所有類 
  81.      * @param jarPath jar檔案路徑 
  82.      * @param childPackage 是否遍歷子包 
  83.      * @return 類的完整名稱 
  84.      */
  85.     privatestatic List<String> getClassNameByJar(String jarPath, boolean childPackage) {  
  86.         List<String> myClassName = new ArrayList<String>();  
  87.         String[] jarInfo = jarPath.split("!");  
  88.         String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/"));  
  89.         String packagePath = jarInfo[1].substring(1);  
  90.         try {  
  91.             JarFile jarFile = new JarFile(jarFilePath);  
  92.             Enumeration<JarEntry> entrys = jarFile.entries();  
  93.             while (entrys.hasMoreElements()) {  
  94.                 JarEntry jarEntry = entrys.nextElement();  
  95.                 String entryName = jarEntry.getName();  
  96.                 if (entryName.endsWith(".class")) {  
  97.                     if (childPackage) {  
  98.                         if (entryName.startsWith(packagePath)) {  
  99.                             entryName = entryName.replace("/"".").substring(0, entryName.lastIndexOf("."));  
  100.                             myClassName.add(entryName);  
  101.                         }  
  102.                     } else {  
  103.                         int index = entryName.lastIndexOf("/");  
  104.                         String myPackagePath;  
  105.                         if (index != -1) {  
  106.                             myPackagePath = entryName.substring(0, index);  
  107.                         } else {  
  108.                             myPackagePath = entryName;  
  109.                         }  
  110.                         if (myPackagePath.equals(packagePath)) {  
  111.                             entryName = entryName.replace("/"".").substring(0, entryName.lastIndexOf("."));  
  112.                             myClassName.add(entryName);  
  113.                         }  
  114.                     }  
  115.                 }  
  116.             }  
  117.         } catch (Exception e) {  
  118.             e.printStackTrace();  
  119.         }  
  120.         return myClassName;  
  121.     }  
  122.     /** 
  123.      * 從所有jar中搜索該包,並獲取該包下所有類 
  124.      * @param urls URL集合 
  125.      * @param packagePath 包路徑 
  126.      * @param childPackage 是否遍歷子包 
  127.      * @return 類的完整名稱 
  128.      */
  129.     privatestatic List<String> getClassNameByJars(URL[] urls, String packagePath, boolean childPackage) {  
  130.         List<String> myClassName = new ArrayList<String>();  
  131.         if (urls != null) {  
  132.             for (int i = 0; i < urls.length; i++) {  
  133.                 URL url = urls[i];  
  134.                 String urlPath = url.getPath();  
  135.                 // 不必搜尋classes資料夾
  136.                 if (urlPath.endsWith("classes/")) {  
  137.                     continue;  
  138.                 }  
  139.                 String jarPath = urlPath + "!/" + packagePath;  
  140.                 myClassName.addAll(getClassNameByJar(jarPath, childPackage));  
  141.             }  
  142.         }  
  143.         return myClassName;  
  144.     }  
  145. }  

由於我們並不確定jar包生成時採用的哪種方式,如果採用預設生成jar包的方式,那我們通過Thread.currentThread().getContextClassLoader().getResource()是獲取不到的,因此我增加了從所有jar包中搜索提供的包域名,這樣功能就完善了很多。

那麼就此關於“如何遍歷包中所有類”就結束了,PackageUtil這個類的功能還有些少,不排除日後進一步完善的可能,如果大家關於這個util有什麼新的需求或者建議,隨時歡迎大家提出。發現bug的,也請及時通知我以便改進。

相關推薦

Java所有方法註解

|| asm 服務器 ret nec next 代碼 自定義 tco 一.代碼實例 import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.l

Java所有

package com.itkt.mtravel.hotel.util;   import java.io.File;   import java.net.URL;   import java.net.URLClassLoader;   import java.uti

Java: 獲取jar某個的serialVersionUID(序列版本id)

2018.11.02 文章目錄 前言 方法 前言 在《序列化及Java Serializable序列化介面》一文,我介紹了一個case:一個已上線的版本中包含了未定義serialVersionUID序

javaList的map的幾種方法

 Stueng 類 public class Student { private String name; private int age; private int taller; public Student( String name, int age, int ta

java呼叫預設

Class c; try { c = Class.forName("co_dc_tpc_TamperProofCodeService"); Method m = c.g

Java.lang軟體

java.lang軟體包是java語言的核心部分,它提供了java中的基礎類。 java.lang.Object,這是java.lang的根類,也是所有java類的超類。在構造java類的例項時,都先呼叫Object中的預設構造方法。類 java.lang.Class&

java 指定所有,返回完整名。工具,可以直接拷入使用

1、說明:       此類為本人開發的工具類,具體應用在什麼地方呢。本人在實際專案中,許可權管理這一塊有所應用,應該是許可權這一塊有所需求而開發的。 應用場景說明:許可權資源自動化生產時,使用者點選介面的一鍵生成資源時,介面中就會遍歷指定controller包下所有

獲取所有的註解的值 (java工具

作用:這個工具類主要的作用就是獲取類中的註解的值。 應用場景:做許可權的時候獲取@RequestMapping();的值,自動新增到資料庫中。 /** * getRequestMappingValue方法描述: * 作者:thh

Java一個所有屬性和值

private void bianLi(Object obj){ Field[] fields = obj.getClass().getDeclaredFields(); for(int

存儲所有物體添加到列表(使用GameObject.activeSelf進行判斷)

data des button menus add image game tac self //存儲菜單列表 List<GameObject> subMenu = new List<GameObject>(); //存儲所有子菜單 pu

JAVA 文件夾下的所有文件

with rip [] ring temp emp lin filelist 目錄 JAVA 遍歷文件夾下的所有文件(遞歸調用和非遞歸調用) 1.不使用遞歸的方法調用. public void traverseFolder1(String path) {

java實體的屬性和數據型以及屬性值

取值 .get 數組 所有 system blog ++ 實體bean lds 遍歷實體類的樹形和數據類型一級屬性值 /** * 遍歷實體類的屬性和數據類型以及屬性值 * @param model * @throws NoSuchMe

java學習--java.util常用

ext line 一次 必須 get 拷貝 opera ann lean java.util包被稱為java工具包,裏面包含大部分的工具類 Random 隨機數類 new Random() rd.nextInt() rd.nextInt(100) Scanner 掃描器類

使用foreach文章出現所有單詞的次數

var tweets = [ "Education is showing business the way by using technology to share information. How do we do so safely?", "Enjoy a free

Java指定目錄下的所有檔案

初級Java面試經常會遇到寫一個遞迴遍歷指定資料夾下的所有檔案,今天閒來無事,看了些例子,自己整理一下。希望可以幫助到初學者,順便也算自己的一個筆記,方便以後查閱。 package files; import java.io.File; public class RecursionFi

java同一個之間的的呼叫

如果是靜態方法,直接 類名.方法名即可,如果是非靜態方法,則需new一個物件出來,然後用物件.方法名呼叫如:public class A{public static void T(){System.out.print("這是A類的方法");}public void T2(){System.out.print(

java樹的,包括先序、後序以及廣度優先跟深度優先

先總結一下各種遍歷方式的區別 前序遍歷:根結點 ---> 左子樹 ---> 右子樹 中序遍歷:左子樹---> 根結點 ---> 右子樹 後序遍歷:左子樹 ---> 右子樹 ---> 根結點 廣度優先,從左到右 深度

輸入某二叉樹的前序的結果,請重建出該二叉樹(java實現並測試)

假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。 package ssp; class TreeNode { int val; TreeNod

黑馬程式設計師----Java基礎之IO其它

------- <a href="http://www.itheima.com" target="blank">android培訓</a>、<a href="http://www.itheima.com" target="blank">java培訓</a&g

java二叉樹:前序,後序深度,求葉子節點個數,層次

import java.util.ArrayDeque; import java.util.Queue; public class CreateTree { /** * @param args */ public static void main(Stri