Java 获取方法的参数是List 或 Array的元素类型

复制代码
private void test1() {
    Method[] methods = TestObj.class.getMethods();
    Method listMethod = null;
    Method arrayMethod = null;
    for (Method m : methods) {
        if (m.getName().equals("ListPara")) {
            listMethod = m;
        } else if (m.getName().equals("ArrayPara")) {
            arrayMethod = m;
        }
    }

    Class<?> arrayParaType = arrayMethod.getParameterTypes()[0];
    boolean isArray = arrayParaType.isArray(); //是 Array
    /**
     * 获取 Array 的元素类型
     * */
    Class<?> arrayEleType = arrayParaType.getComponentType();
    if (MenuInfo.class == arrayEleType) {
        System.out.println(arrayEleType.toString());
    }

    Class<?> listParaType = listMethod.getParameterTypes()[0];
    boolean isList = List.class.isAssignableFrom(listParaType); //是 List
    /**
     * 获取 List 的元素类型
     * */
    Type listType = listMethod.getGenericParameterTypes()[0];
    ParameterizedType parameterizedType = (ParameterizedType) listType;
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    Class<?> listEleType = (Class<?>) actualTypeArguments[0];
    if (MenuInfo.class == listEleType) {
        System.out.println(listEleType.toString());
    }
}

class TestObj {
    public void ListPara(List<MenuInfo> menuInfos) {
        //
    }

    public void ArrayPara(MenuInfo[] menuInfos) {
        //
    }
}
相关推荐
小糖学代码2 小时前
LLM系列:1.python入门:3.布尔型对象
linux·开发语言·python
Data_agent2 小时前
1688获得1688店铺详情API,python请求示例
开发语言·爬虫·python
开心香辣派小星2 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式
Halo_tjn3 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
周杰伦fans3 小时前
pycharm之gitignore设置
开发语言·python·pycharm
摆烂z3 小时前
Docker与Jib(maven插件版)实战
java
RainbowSea3 小时前
从 Spring Boot 2.x 到 3.5.x + JDK21:一次完整的生产环境迁移实战
java·spring boot·后端
笨手笨脚の3 小时前
Spring Core常见错误及解决方案
java·后端·spring
weixin_462446233 小时前
【原创实践】python 获取节假日列表 并保存为excel
数据库·python·excel
奶油松果3 小时前
Springboot自动装配 - redis和redission
java·spring boot·redis