Java遍曆包中所有類

來源:互聯網
上載者:User

標籤:int   .class   add   div   rac   with   private   start   jar   

PackageUtil 類 

import java.io.File;import java.net.URL;import java.net.URLClassLoader;import java.util.ArrayList;import java.util.Enumeration;import java.util.List;import java.util.jar.JarEntry;import java.util.jar.JarFile;/** * 擷取包中所有的類 * @author * */public class PackageUtil {    public static void main(String[] args) throws Exception {        String packageName = "com.wang.vo.request.hotel";        // List<String> classNames = getClassName(packageName);        List<String> classNames = getClassName(packageName, false);        if (classNames != null) {            for (String className : classNames) {                System.out.println(className);            }        }    }    /**     * 擷取某包下(包括該包的所有子包)所有類     *      * @param packageName     *            包名     * @return 類的完整名稱     */    public static List<String> getClassName(String packageName) {        return getClassName(packageName, true);    }    /**     * 擷取某包下所有類     *      * @param packageName     *            包名     * @param childPackage     *            是否遍曆子包     * @return 類的完整名稱     */    public static List<String> getClassName(String packageName, boolean childPackage) {        List<String> fileNames = null;        ClassLoader loader = Thread.currentThread().getContextClassLoader();        String packagePath = packageName.replace(".", "/");        URL url = loader.getResource(packagePath);        if (url != null) {            String type = url.getProtocol();            if (type.equals("file")) {                fileNames = getClassNameByFile(url.getPath(), null, childPackage);            } else if (type.equals("jar")) {                fileNames = getClassNameByJar(url.getPath(), childPackage);            }        } else {            fileNames = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage);        }        return fileNames;    }    /**     * 從專案檔擷取某包下所有類     *      * @param filePath     *            檔案路徑     * @param className     *            類名集合     * @param childPackage     *            是否遍曆子包     * @return 類的完整名稱     */    private static List<String> getClassNameByFile(String filePath, List<String> className, boolean childPackage) {        List<String> myClassName = new ArrayList<>();        File file = new File(filePath);        File[] childFiles = file.listFiles();        for (File childFile : childFiles) {            if (childFile.isDirectory()) {                if (childPackage) {                    myClassName.addAll(getClassNameByFile(childFile.getPath(), myClassName, childPackage));                }            } else {                String childFilePath = childFile.getPath();                if (childFilePath.endsWith(".class")) {                    childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9,                            childFilePath.lastIndexOf("."));                    childFilePath = childFilePath.replace("\\", ".");                    myClassName.add(childFilePath);                }            }        }        return myClassName;    }    /**     * 從jar擷取某包下所有類     *      * @param jarPath     *            jar檔案路徑     * @param childPackage     *            是否遍曆子包     * @return 類的完整名稱     */    private static List<String> getClassNameByJar(String jarPath, boolean childPackage) {        List<String> myClassName = new ArrayList<>();        String[] jarInfo = jarPath.split("!");        String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/"));        String packagePath = jarInfo[1].substring(1);        try {            JarFile jarFile = new JarFile(jarFilePath);            Enumeration<JarEntry> entrys = jarFile.entries();            while (entrys.hasMoreElements()) {                JarEntry jarEntry = entrys.nextElement();                String entryName = jarEntry.getName();                if (entryName.endsWith(".class")) {                    if (childPackage) {                        if (entryName.startsWith(packagePath)) {                            entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf("."));                            myClassName.add(entryName);                        }                    } else {                        int index = entryName.lastIndexOf("/");                        String myPackagePath;                        if (index != -1) {                            myPackagePath = entryName.substring(0, index);                        } else {                            myPackagePath = entryName;                        }                        if (myPackagePath.equals(packagePath)) {                            entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf("."));                            myClassName.add(entryName);                        }                    }                }            }        } catch (Exception e) {            e.printStackTrace();        }        return myClassName;    }    /**     * 從所有jar中搜尋該包,並擷取該包下所有類     *      * @param urls     *            URL集合     * @param packagePath     *            包路徑     * @param childPackage     *            是否遍曆子包     * @return 類的完整名稱     */    private static List<String> getClassNameByJars(URL[] urls, String packagePath, boolean childPackage) {        List<String> myClassName = new ArrayList<>();        if (urls != null) {            for (int i = 0; i < urls.length; i++) {                URL url = urls[i];                String urlPath = url.getPath();                // 不必搜尋classes檔案夾                if (urlPath.endsWith("classes/")) {                    continue;                }                String jarPath = urlPath + "!/" + packagePath;                myClassName.addAll(getClassNameByJar(jarPath, childPackage));            }        }        return myClassName;    }}

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

  轉載至https://www.2cto.com/kf/201211/169865.html

Java遍曆包中所有類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.