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

因为项目长时间积累接口比较多,需要删除不用接口,这里通过工具类递归遍历目录获取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 packageName, List<InterfaceDo> urlList) throws Exception {
        Assert.notNull(urlList, "不可为空");
        File dir = new File(filePath);
        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                String fileName = file.getName();
                System.out.println("开始扫描文件:" + fileName + ",包名:" + packageName);
                if (fileName.endsWith(".java")) {
                    String className = null;
                    if (packageName != null) {
                        className = packageName + '.' + fileName.substring(0, fileName.length() - 5);
                    } else {
                        className = fileName.substring(0, fileName.length() - 5);
                    }
                    className = className.replaceAll(removeStr, "").trim();
                    //加载类
                    Class<?> aClass = null;
                    try {
                        aClass = classLoader.loadClass(className);
                    } catch (Error e) {
                        System.out.println(e);
                        continue;
                    } catch (Exception e) {
                        System.out.println(e);
                        continue;
                    }
                    //判断下controller 接口是否有注解 @Controller @restController
                    if (aClass.getAnnotation(org.springframework.stereotype.Controller.class) == null
                        && aClass.getAnnotation(org.springframework.web.bind.annotation.RestController.class) == null) {
                        continue;
                    }
                    //判断下是否存在接口@RequestMapper注解
                    if (!containMapperAnnotationLsByClass(aClass)) {
                        continue;
                    }
                    //获取所有public方法
                    Method[] methods = aClass.getMethods();
                    for (int i = 0; i < methods.length; i++) {
                        Method method = methods[i];
                        if (Modifier.isPublic(method.getModifiers()) && containMapperAnnotationLsByMonth(method)) {

                            //获取类上url
                            String url1[] = getMappingPathUrlByClass(aClass);
                            //获取方法url
                            String url2 = getMappingPathUrlByMonth(method);
                            //格式化
                            if (!"/".equals(url2.substring(0, 1))) {
                                url2 = "/" + url2;
                            }
                            RequestMethod requestMethod = getRequestMethodByMonth(method);
                            if (url1 != null && url1.length > 0) {
                                for (String url : url1) {
                                    //第一个是否以/开头
                                    if (!"/".equals(url.substring(0, 1))) {
                                        url = "/" + url;
                                    }
                                    InterfaceDo interfaceDo = new InterfaceDo();
                                    interfaceDo.setUrl(url + url2);
                                    interfaceDo.setRequestMethod(requestMethod);
                                    urlList.add(interfaceDo);
                                }
                            } else {
                                InterfaceDo interfaceDo = new InterfaceDo();
                                interfaceDo.setUrl(url2);
                                interfaceDo.setRequestMethod(requestMethod);
                                urlList.add(interfaceDo);
                            }
                        }
                    }
                } else if (file.isDirectory()) {
                    String subPackageName = null;
                    if (packageName != null) {
                        subPackageName = packageName + '.' + fileName;
                    } else {
                        subPackageName = fileName;
                    }
                    getAllIntefaces(file.getPath(), subPackageName, urlList);
                }
            }
        }
    }

    /**
     * 获取类上url
     * 类上可指定多个url
     */
    private String[] getMappingPathUrlByClass(Class clazz) {
        String[] value = null;
        for (Class aClass : mapperAnnotationLs) {
            Annotation annotation = clazz.getAnnotation(aClass);
            if (annotation != null) {
                value = getAnnotationValue(annotation);
            }
        }
        return value;
    }

    /**
     * 获取方法上url
     */
    private String getMappingPathUrlByMonth(Method clazz) {
        String[] value = null;
        for (Class aClass : mapperAnnotationLs) {
            Annotation annotation = clazz.getAnnotation(aClass);
            value = getAnnotationValue(annotation);
        }
        return Optional.ofNullable(value).filter(k -> k.length > 0).map(k -> k[0]).orElse("");
    }

    /**
     * 获取注解中存在接口注解的value
     * @param annotation
     * @return
     */
    private String[] getAnnotationValue(Annotation annotation) {
        String[] value = null;
        if (annotation != null) {
            if (annotation instanceof RequestMapping) {
                value = ((RequestMapping)annotation).value();
            } else if (annotation instanceof PostMapping) {
                value = ((PostMapping)annotation).value();
            } else if (annotation instanceof GetMapping) {
                value = ((GetMapping)annotation).value();
            } else if (annotation instanceof PutMapping) {
                value = ((PutMapping)annotation).value();
            } else if (annotation instanceof DeleteMapping) {
                value = ((DeleteMapping)annotation).value();
            } else if (annotation instanceof PatchMapping) {
                value = ((PatchMapping)annotation).value();
            }
        }
        return value;
    }

    /**
     * 获取ApiOperation方法级别的注解
     * @param method
     * @return
     */
    private String getApiOperationByMethod(Method method) {

        return null;
    }

    /**
     * 获取方法级别的注解
     * @param clazz
     * @return
     */
    private RequestMethod getRequestMethodByMonth(Method clazz) {
        RequestMethod method = null;
        for (Class aClass : mapperAnnotationLs) {
            Annotation annotation = clazz.getAnnotation(aClass);
            if (annotation != null) {
                if (annotation instanceof RequestMapping) {
                    //空
                } else if (annotation instanceof PostMapping) {
                    method = RequestMethod.POST;
                } else if (annotation instanceof GetMapping) {
                    method = RequestMethod.GET;
                } else if (annotation instanceof PutMapping) {
                    method = RequestMethod.PUT;
                } else if (annotation instanceof DeleteMapping) {
                    method = RequestMethod.DELETE;
                } else if (annotation instanceof PatchMapping) {
                    method = RequestMethod.PATCH;
                }
            }
        }
        return method;
    }

    /**
     * 判断方法是否包含注解
     */
    private boolean containMapperAnnotationLsByMonth(Method method) {
        for (Class aClass : mapperAnnotationLs) {
            if (method.getAnnotation(aClass) != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断类是否包含注解
     */
    private boolean containMapperAnnotationLsByClass(Class clazz) {
        for (Class aClass : mapperAnnotationLs) {
            if (clazz.getAnnotation(aClass) != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 接口信息对象
     */
    class InterfaceDo {
        /**
         * 描述
         */
        private String name;
        /**
         * url
         */
        private String url;

        /**
         * 请求类型
         */
        private RequestMethod requestMethod;

        public InterfaceDo() {
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public RequestMethod getRequestMethod() {
            return requestMethod;
        }

        public void setRequestMethod(RequestMethod requestMethod) {
            this.requestMethod = requestMethod;
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("InterfaceDo{");
            sb.append("name='").append(name).append('\'');
            sb.append(", url='").append(url).append('\'');
            sb.append(", requestMethod=").append(requestMethod);
            sb.append('}');
            return sb.toString();
        }
    }

}

我们只需要传入一个filePath,也就是你所涉及接口主目录。

目前工具类需要放入项目包里面,与你要导出项目在一个环境即可。

其他方式也有很多。这里先介绍这种

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要通过Java反射获取父类和子类的所有属性,我们可以使用Class类的getFields()和getDeclaredFields()方法。 - getFields()方法可以获取类中所有公共的(即用public修饰的)属性,包括父类中的公共属性。返回的是一个数组,其中包含了所有公共属性的Field对象。 - getDeclaredFields()方法可以获取类中所有声明的属性,包括私有的、受保护的和默认访问权限的属性,但不包括父类中的属性。返回的也是一个数组,其中包含了所有声明的属性的Field对象。 我们可以先获取子类的Class对象,然后利用getFields()和getDeclaredFields()方法获取子类自己声明的属性和从父类继承的公共属性。 再获取父类的Class对象,利用getFields()方法获取父类的公共属性。 下面是一个示例代码: ```java import java.lang.reflect.Field; public class ReflectionExample { public static void main(String[] args) { Child child = new Child(); // 获取子类Class对象 Class<?> childClass = child.getClass(); // 获取子类自己声明的属性和从父类继承的公共属性 Field[] childFields = childClass.getDeclaredFields(); for (Field field : childFields) { System.out.println(field.getName()); } // 获取父类Class对象 Class<?> parentClass = childClass.getSuperclass(); // 获取父类的公共属性 Field[] parentFields = parentClass.getFields(); for (Field field : parentFields) { System.out.println(field.getName()); } } } class Parent { public int parentField; } class Child extends Parent { private String childField; } ``` 在上面的示例中,我们创建了一个Parent类和一个Child类。Child类继承自Parent类,并在自己中声明了一个private的childField属性。 运行示例代码,结果会打印出子类和父类的所有属性名: ``` childField parentField ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值