代码片段-扫描JAR中对象

public static <T> List<Class<T>> scanSubClass(Class<T> pclazz, boolean mustbeCanNewInstance) {
        if (pclazz == null) {
            log.error("scanClass: parent clazz is null");
            return null;
        }

        File jarsDir = new File(PathKit.getWebRootPath() + "/WEB-INF/lib");
        if (jarsDir.exists() && jarsDir.isDirectory()) {
            File[] jarFiles = jarsDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    String name = pathname.getName().toLowerCase();
                    return name.endsWith(".jar") && name.startsWith("je");
                }
            });

            if (jarFiles != null && jarFiles.length > 0) {
                for (File f : jarFiles) {
                    try {
                        System.out.println("jar path: "+f.getPath());
                        classList.addAll(scanSubClass(pclazz, new JarFile(f), mustbeCanNewInstance));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return classList;
    }

  上述代码可以直接扫描JAR包中的对象文件,Spring配置文件中的Bean也是通过这样的扫描再进行反射创建对象的。

posted @ 2016-07-19 21:38  saga5998  阅读(190)  评论(0)    收藏  举报