java过去指定包下的所有类_spring获取指定包下面的所有类

importjava.io.IOException;importjava.util.HashSet;importjava.util.Set;importorg.springframework.context.ResourceLoaderAware;importorg.springframework.core.io.Resource;importorg.springframework.core.io.ResourceLoader;importorg.springframework.core.io.support.ResourcePatternResolver;importorg.springframework.core.io.support.ResourcePatternUtils;importorg.springframework.core.type.classreading.CachingMetadataReaderFactory;importorg.springframework.core.type.classreading.MetadataReader;importorg.springframework.core.type.classreading.MetadataReaderFactory;importorg.springframework.util.ClassUtils;importorg.springframework.util.SystemPropertyUtils;importxxxxx.mall.common.application.MallApplication;importxxxxx.common.assertion.Assert;/*** SPRING扫描包下面的类

*

* @project common-utils

* @fileName Scaner.java

* @Description

*@authorlight-zhang

* @date 2019年5月5日

*@version1.0.0*/

public class ScanSupport implementsResourceLoaderAware {/*** Spring容器注入*/

privateResourceLoader resourceLoader;private ResourcePatternResolver resolver =ResourcePatternUtils.getResourcePatternResolver(resourceLoader);private MetadataReaderFactory metadataReaderFactory = newCachingMetadataReaderFactory(resourceLoader);private static final String FULLTEXT_SACN_PACKAGE_PATH = "fulltext.scan.package";/*** set注入对象*/@Overridepublic voidsetResourceLoader(ResourceLoader resourceLoader) {this.resourceLoader =resourceLoader;

}/*** 利用spring提供的扫描包下面的类信息,再通过classfrom反射获得类信息

*

*@paramscanPath

*@return*@throwsIOException*/

public Set> doScan(String scanPath) throwsIOException {

Set> classes = new HashSet>();

String packageSearchPath=ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX

.concat(ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(scanPath))

.concat("/**/*.class"));

Resource[] resources=resolver.getResources(packageSearchPath);

MetadataReader metadataReader= null;for(Resource resource : resources) {if(resource.isReadable()) {

metadataReader=metadataReaderFactory.getMetadataReader(resource);try{if (metadataReader.getClassMetadata().isConcrete()) {//当类型不是抽象类或接口在添加到集合

classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));

}

}catch(Exception e) {

e.printStackTrace();

}

}

}returnclasses;

}/*** 指定包下面的类信息

*

*@return多个类信息*/

public static Set>classInfos() {try{

String scanPath=MallApplication.getApplicationContext().getEnvironment()

.getProperty(FULLTEXT_SACN_PACKAGE_PATH);return newScanSupport().doScan(scanPath);

}catch(Exception e) {

Assert.RuntimeException("扫描包类信息错误");

}return null;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值