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

    package com.MyUtils.file;  

[java] view plain copy

    import java.io.File;  
    import java.io.FileFilter;  
    import java.io.IOException;  
    import java.net.JarURLConnection;  
    import java.net.URI;  
    import java.net.URISyntaxException;  
    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;  
      
      
    /** 
     * 扫描包下路径  
     * 包括本地文件和jar包文件 
     * @author ljb 
     * 
     */  
    public class ScanningFile {  
          
        private Class<?> superStrategy = String.class;//接口类class 用于过滤 可以不要  
          
        private List<Class<? extends String>> eleStrategyList = new ArrayList<Class<? extends String>>();  
          
        private ClassLoader classLoader = ScanningFile.class.getClassLoader();//默认使用的类加载器  
          
        private static final String STARATEGY_PATH = "com.MyUtils.file";//需要扫描的策略包名  
          
        public static void main(String[] args) {  
            ScanningFile s = new ScanningFile();  
            s.addClass();  
        }  
           
        /** 
         * 获取包下所有实现了superStrategy的类并加入list 
         */  
        private void addClass(){  
            URL url = classLoader.getResource(STARATEGY_PATH.replace(".", "/"));  
            String protocol = url.getProtocol();    
            if ("file".equals(protocol)) {    
                // 本地自己可见的代码    
                findClassLocal(STARATEGY_PATH);  
            } else if ("jar".equals(protocol)) {    
                // 引用jar包的代码    
                findClassJar(STARATEGY_PATH);    
            }    
        }  
          
        /** 
         * 本地查找 
         * @param packName 
         */  
        private void findClassLocal(final String packName){  
            URI url = null ;  
            try {  
                url = classLoader.getResource(packName.replace(".", "/")).toURI();  
            } catch (URISyntaxException e1) {  
                throw new RuntimeException("未找到策略资源");  
            }  
              
            File file = new File(url);  
            file.listFiles(new FileFilter() {  
                      
                    public boolean accept(File chiFile) {  
                        if(chiFile.isDirectory()){  
                            findClassLocal(packName+"."+chiFile.getName());  
                        }  
                        if(chiFile.getName().endsWith(".class")){  
                            Class<?> clazz = null;  
                            try {  
                                clazz = classLoader.loadClass(packName + "." + chiFile.getName().replace(".class", ""));  
                            } catch (ClassNotFoundException e) {  
                                e.printStackTrace();  
                            }  
                            System.out.println(chiFile);  
                            if(superStrategy.isAssignableFrom(clazz)){  
                                eleStrategyList.add((Class<? extends String>) clazz);  
                            }  
                            return true;  
                        }  
                        return false;  
                    }  
                });  
               
        }  
          
        /** 
         * jar包查找 
         * @param packName 
         */  
        private void findClassJar(final String packName){  
            String pathName = packName.replace(".", "/");  
            JarFile jarFile  = null;  
            try {  
                URL url = classLoader.getResource(pathName);  
                JarURLConnection jarURLConnection  = (JarURLConnection )url.openConnection();  
                jarFile = jarURLConnection.getJarFile();    
            } catch (IOException e) {  
                throw new RuntimeException("未找到策略资源");  
            }  
              
            Enumeration<JarEntry> 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);    
                        }    
                        findClassJar(prefix);  
                    }  
                    if(jarEntry.getName().endsWith(".class")){  
                        Class<?> clazz = null;  
                        try {  
                            clazz = classLoader.loadClass(jarEntry.getName().replace("/", ".").replace(".class", ""));  
                        } catch (ClassNotFoundException e) {  
                            e.printStackTrace();  
                        }  
                        if(superStrategy.isAssignableFrom(clazz)){  
                            eleStrategyList.add((Class<? extends String>) clazz);  
                        }  
                    }  
                }  
                  
            }  
               
         }  
          
    }  
  1. package com.MyUtils.file;  
[java] view plain copy
  1. import java.io.File;  
  2. import java.io.FileFilter;  
  3. import java.io.IOException;  
  4. import java.net.JarURLConnection;  
  5. import java.net.URI;  
  6. import java.net.URISyntaxException;  
  7. import java.net.URL;  
  8. import java.util.ArrayList;  
  9. import java.util.Enumeration;  
  10. import java.util.List;  
  11. import java.util.jar.JarEntry;  
  12. import java.util.jar.JarFile;  
  13.   
  14.   
  15. /** 
  16.  * 扫描包下路径  
  17.  * 包括本地文件和jar包文件 
  18.  * @author ljb 
  19.  * 
  20.  */  
  21. public class ScanningFile {  
  22.       
  23.     private Class<?> superStrategy = String.class;//接口类class 用于过滤 可以不要  
  24.       
  25.     private List<Class<? extends String>> eleStrategyList = new ArrayList<Class<? extends String>>();  
  26.       
  27.     private ClassLoader classLoader = ScanningFile.class.getClassLoader();//默认使用的类加载器  
  28.       
  29.     private static final String STARATEGY_PATH = "com.MyUtils.file";//需要扫描的策略包名  
  30.       
  31.     public static void main(String[] args) {  
  32.         ScanningFile s = new ScanningFile();  
  33.         s.addClass();  
  34.     }  
  35.        
  36.     /** 
  37.      * 获取包下所有实现了superStrategy的类并加入list 
  38.      */  
  39.     private void addClass(){  
  40.         URL url = classLoader.getResource(STARATEGY_PATH.replace(".""/"));  
  41.         String protocol = url.getProtocol();    
  42.         if ("file".equals(protocol)) {    
  43.             // 本地自己可见的代码    
  44.             findClassLocal(STARATEGY_PATH);  
  45.         } else if ("jar".equals(protocol)) {    
  46.             // 引用jar包的代码    
  47.             findClassJar(STARATEGY_PATH);    
  48.         }    
  49.     }  
  50.       
  51.     /** 
  52.      * 本地查找 
  53.      * @param packName 
  54.      */  
  55.     private void findClassLocal(final String packName){  
  56.         URI url = null ;  
  57.         try {  
  58.             url = classLoader.getResource(packName.replace(".""/")).toURI();  
  59.         } catch (URISyntaxException e1) {  
  60.             throw new RuntimeException("未找到策略资源");  
  61.         }  
  62.           
  63.         File file = new File(url);  
  64.         file.listFiles(new FileFilter() {  
  65.                   
  66.                 public boolean accept(File chiFile) {  
  67.                     if(chiFile.isDirectory()){  
  68.                         findClassLocal(packName+"."+chiFile.getName());  
  69.                     }  
  70.                     if(chiFile.getName().endsWith(".class")){  
  71.                         Class<?> clazz = null;  
  72.                         try {  
  73.                             clazz = classLoader.loadClass(packName + "." + chiFile.getName().replace(".class"""));  
  74.                         } catch (ClassNotFoundException e) {  
  75.                             e.printStackTrace();  
  76.                         }  
  77.                         System.out.println(chiFile);  
  78.                         if(superStrategy.isAssignableFrom(clazz)){  
  79.                             eleStrategyList.add((Class<? extends String>) clazz);  
  80.                         }  
  81.                         return true;  
  82.                     }  
  83.                     return false;  
  84.                 }  
  85.             });  
  86.            
  87.     }  
  88.       
  89.     /** 
  90.      * jar包查找 
  91.      * @param packName 
  92.      */  
  93.     private void findClassJar(final String packName){  
  94.         String pathName = packName.replace(".""/");  
  95.         JarFile jarFile  = null;  
  96.         try {  
  97.             URL url = classLoader.getResource(pathName);  
  98.             JarURLConnection jarURLConnection  = (JarURLConnection )url.openConnection();  
  99.             jarFile = jarURLConnection.getJarFile();    
  100.         } catch (IOException e) {  
  101.             throw new RuntimeException("未找到策略资源");  
  102.         }  
  103.           
  104.         Enumeration<JarEntry> jarEntries = jarFile.entries();  
  105.         while (jarEntries.hasMoreElements()) {  
  106.             JarEntry jarEntry = jarEntries.nextElement();  
  107.             String jarEntryName = jarEntry.getName();  
  108.               
  109.             if(jarEntryName.contains(pathName) && !jarEntryName.equals(pathName+"/")){  
  110.                 //递归遍历子目录  
  111.                 if(jarEntry.isDirectory()){  
  112.                     String clazzName = jarEntry.getName().replace("/"".");  
  113.                     int endIndex = clazzName.lastIndexOf(".");   
  114.                     String prefix = null;    
  115.                     if (endIndex > 0) {    
  116.                         prefix = clazzName.substring(0, endIndex);    
  117.                     }    
  118.                     findClassJar(prefix);  
  119.                 }  
  120.                 if(jarEntry.getName().endsWith(".class")){  
  121.                     Class<?> clazz = null;  
  122.                     try {  
  123.                         clazz = classLoader.loadClass(jarEntry.getName().replace("/"".").replace(".class"""));  
  124.                     } catch (ClassNotFoundException e) {  
  125.                         e.printStackTrace();  
  126.                     }  
  127.                     if(superStrategy.isAssignableFrom(clazz)){  
  128.                         eleStrategyList.add((Class<? extends String>) clazz);  
  129.                     }  
  130.                 }  
  131.             }  
  132.               
  133.         }  
  134.            
  135.      }  
  136.       

猜你喜欢

转载自www.cnblogs.com/tiancai/p/9177217.html