扫描文件找到mapper对应的表(草稿版本,后期手写Spring加载bean使用)

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.SneakyThrows;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * @ProjectName: ehm-community
 * @Package: PACKAGE_NAME
 * @ClassName: A
 * @Author: xzj
 * @Description:
 * @Date: 2022/7/4 15:01
 * @Version: 1.0
 */
public class A {
    public static void main(String[] args) throws IOException {
        Files.walkFileTree(Paths.get("./"), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
//                System.out.println("=====>" + dir);
                return super.preVisitDirectory(dir, attrs);
            }

            @SneakyThrows
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                //找到所有dao的class文件
                if(file.toString().endsWith("Mapper.class")){
                    //去掉多余前缀
                    int i = file.toString().indexOf("\\target\\classes");
                    String replace = file.toString()
                            .substring(i + 16)
                            .replace('\\', '.')
                            .replace(".class","");
                    System.out.println(replace);
                    Class<?> clz = Class.forName(replace);
                    Type[] genericInterfaces = clz.getGenericInterfaces();
                    ParameterizedType parameterizedType = (ParameterizedType) genericInterfaces[0];
//                    System.out.println(parameterizedType);
                    if(parameterizedType.getActualTypeArguments()[0] != null){
                        Class<?> aClass = Class.forName(parameterizedType.getActualTypeArguments()[0].getTypeName());
//                        System.out.println(aClass);
                        TableName annotation = aClass.getAnnotation(TableName.class);
                        String value = annotation.value();
                        System.out.println(value);
                    }
                }
                return super.visitFile(file, attrs);
            }
        });

    }
}

 

posted @ 2022-07-04 15:55  java架构师1  阅读(78)  评论(0)    收藏  举报