java 根据包的路径获取到该包下面所有的class类

import lombok.SneakyThrows;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class ClassLoadUtil {

    private static final MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();

    private static final Environment environment = new StandardEnvironment();

    private static final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();


    /**
     * 根据包路径找到所有的改包下面所有的class
     * 例org.recipe.draw.**.mapper与MapperScan注解的写法一致
     */
    @SneakyThrows
    public static List> getClassByPackage(String... pathArray) {
        Set> set = new HashSet<>();
        for (String path : pathArray) {
            String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    resolveBasePackage(path) + '/' + "**/*.class";
            Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    Class clazz = ClassLoader.getSystemClassLoader().loadClass(metadataReader.getClassMetadata().getClassName());
                    set.add(clazz);
                }
            }
        }
        return new ArrayList<>(set);
    }

    private static String resolveBasePackage(String basePackage) {
        return ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(basePackage));
    }

    public static void main(String[] args) {
        List> list = getClassByPackage("org.demo.demo");
        list.forEach(aClass -> System.out.println(aClass.getName()));
    }


}

你可能感兴趣的:(java,开发语言)