获取类的子类

原理:

1、扫描指定路劲下的JAVA文件

2、利用反射

package com.util;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 功能描述:扫描工具类
 * 作者:唐泽齐
 */
public class ScanUtil {

    public static <T extends Object> void scanList(String scan, Class<T> clazz, List<T> list) throws Throwable {
        Stream<Path> walk = Files.walk(Paths.get(scan));
        walk
                .filter(Files::isRegularFile)
                .map(path ->
                        path.toString().replaceAll(new String("\\\\"), ".").replaceAll("src.", "")
                )
                .filter(p -> p.endsWith(".java")).map(p ->
                {
                    try {
                        return Class.forName(p.replaceAll(".java", ""));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        return null;
                    }
                }
        )
                .filter(Objects::nonNull)
                .filter(p -> clazz.isAssignableFrom(p))
                .map(p -> {
                    try {
                        return p.newInstance();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                        return null;
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                        return null;
                    }
                }).filter(Objects::nonNull)
                .forEach(p -> {
                    list.add((T) p);
                });
    }
}

 

posted on 2022-07-13 17:59  instr  阅读(278)  评论(0编辑  收藏  举报

导航