Java反射获取项目所有web接口

该代码示例展示了一个Java工具类,用于遍历指定目录下的Java源代码文件,通过反射获取类及SpringMvc注解,主要用于识别和删除不再使用的接口。工具类首先初始化项目路径,然后递归扫描文件,查找包含特定注解的接口,并提取其URL和请求方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为项目长时间积累接口比较多,需要删除不用接口,这里通过工具类递归遍历目录获取calss进行反射创建,获取接口方法以及相关SpringMvc注解,并进行解析。其他方式有很多,目前需求这个就可满足。

直接放入代码

package cn.crl.report;

import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 类工具
 */
public class ClassUtils {

    private static final String removeStr = "src.main.java.";

    private static final String commonPath = "\\src\\main\\java";

    private URL projectPath;

    private URLClassLoader classLoader;

    private String projectPathStr;

    /**
     * 映射器注解
     */
    private static final List<Class> mapperAnnotationLs = new ArrayList() {
  
  {
        add(RequestMapping.class);
        add(PostMapping.class);
        add(GetMapping.class);
        add(PutMapping.class);
        add(DeleteMapping.class);
        add(PatchMapping.class);
    }};

    public static void main(String[] args) throws Exception {
        ClassUtils classUtils = new ClassUtils("E:\\xmdome\\crl-report-form\\crl-report-form-api");
        List<InterfaceDo> arrayList = new ArrayList<>();
        classUtils.getAllIntefaces(classUtils.projectPathStr, null, arrayList);
        arrayList.forEach(System.out::println);
    }

    public ClassUtils(String filePath) {
        init(filePath);
    }

    //初始化
    private void init(String filePath) {
        try {
            this.projectPathStr = filePath + commonPath;
            File file = new File(projectPathStr);
            if (file == null || !file.exists()) {
                //创建下
                throw new RuntimeException("当前目录不存在");
            }
            projectPath = file.toURI().toURL();
            //加载文件
            classLoader = new URLClassLoader(new URL[] {projectPath});
        } catch (Exception e) {
            System.out.println("文件不存在" + e);
        }
    }

    /**
     * @param filePath
     * @param packageName
     * @return
     * @throws Exception
     */
    public void getAllIntefaces(String filePath, String 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值