栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 扫描包下所有类(包括jar包) 加强版

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 扫描包下所有类(包括jar包) 加强版

package com.iotcomm.poleoperationmanagement.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public class ScanningFileUtil {

    private List classes;
    private ClassLoader classLoader = ScanningFileUtil.class.getClassLoader();//默认使用的类加载器

    public static void main(String[] args) {
        ScanningFileUtil scanningFileUtil = new ScanningFileUtil();
        List classes = scanningFileUtil.searchClasses("com.iotcomm",true);
        for(Class clazz : classes){
            System.out.println(clazz.getName());
        }
    }

    
    public List searchClasses(String classPath,boolean needSearchInJar){
        classes = new ArrayList<>();
        try {
            if(needSearchInJar) {
                Enumeration urls = classLoader.getResources(classPath.replace(".", "/"));
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();
                    String protocol = url.getProtocol();
                    if ("file".equals(protocol)) {
                        // 本地自己可见的代码
                        findClassLocal(url.toURI(), classPath);
                    } else if ("jar".equals(protocol)) {
                        // 引用jar包的代码
                        findClassJar(url, classPath.replace(".", "/"));
                    }
                }
            }else{
                URI uri = classLoader.getResource(classPath.replace(".", "/")).toURI();
                findClassLocal(uri, classPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classes;
    }

    
    private void findClassLocal(URI uri,String packName)throws Exception{
        File file = new File(uri);
        file.listFiles(new FileFilter() {
            public boolean accept(File chiFile) {
            if(chiFile.isDirectory()){
                String subPackName =  packName+"."+chiFile.getName();
                try {
                    URI subUrl = classLoader.getResource(subPackName.replace(".", "/")).toURI();
                    findClassLocal(subUrl,subPackName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(chiFile.getName().endsWith(".class")){
                Class clazz = null;
                try {
                    clazz = classLoader.loadClass(packName + "." + chiFile.getName().replace(".class", ""));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                classes.add(clazz);
                return true;
            }
            return false;
        }
        });

    }

    
    private void findClassJar(URL url,String pathName) throws IOException {
        JarFile jarFile  = null;
        try {
            JarURLConnection jarURLConnection  = (JarURLConnection )url.openConnection();
            jarFile = jarURLConnection.getJarFile();
        } catch (IOException e) {
            throw new RuntimeException("未找到策略资源");
        }

        Enumeration jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();

            if(jarEntryName.contains(pathName) && !jarEntryName.equals(pathName+"/")){
                //递归遍历子目录
                if(jarEntry.isDirectory()){
                    String clazzName = jarEntry.getName().replace("/", ".");
                    int endIndex = clazzName.lastIndexOf(".");
                    String prefix = null;
                    if (endIndex > 0) {
                        prefix = clazzName.substring(0, endIndex);
                    }
                    prefix = prefix.replace(".", "/");
                    Enumeration subUrls = classLoader.getResources(prefix);
                    while (subUrls.hasMoreElements()) {
                        URL subUrl = subUrls.nextElement();
                        if (subUrl.getPath().startsWith(url.getPath())) {//子目录以父目录作为开始,保证是同一个jar包内
                            findClassJar(subUrl,prefix);
                        }
                    }

                }
                if(jarEntry.getName().endsWith(".class")){
                    Class clazz = null;
                    try {
                        clazz = classLoader.loadClass(jarEntry.getName().replace("/", ".").replace(".class", ""));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    classes.add(clazz);
                }
            }

        }

    }

}

此代码参考了以下网址的源代码,加以改进
Java 扫描包下所有类(包括jar包)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/285377.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号