java中扫描某个包下的所有类

spring

  • spring中提供的包扫描Demo

spring中提供的包扫描Demo

private List<Object> scan() {
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        //ResourceLoader resourceLoader 对象由spring注入
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
        Resource[] resources;
        try {
            resources = resolver.getResources("classpath*:" + classPath);
        } catch (IOException e) {
            log.error("扫描失败,请检查包名,{}",FastJsonUtils.toString(e));
            throw new RestException(String.format("扫描失败,请检查包名,%s",FastJsonUtils.toString(e)));
        }
        List<Object> list = new ArrayList();
        for (Resource r : resources) {
            MetadataReader reader = null;
            try {
                reader = metaReader.getMetadataReader(r);
                String className = reader.getClassMetadata().getClassName();
                Class aClass =  Class.forName(className);
                Object obj = aClass.newInstance();
                list.add(obj);
            
            } catch (Exception e) {
                e.printStackTrace();
                log.error("无法创建模块导出对象,请检查,{}",FastJsonUtils.toString(e));
                throw new RestException(String.format("无法创建模块导出对象,请检查,%s",FastJsonUtils.toString(e)));
            }
        }
        return list;
    }

你可能感兴趣的:(spring)