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) {
        //
    }
}
相关推荐
1登峰造极8 小时前
uniapp 运行安卓报错reportJSException >>>> exception function:createInstanceContext, exception:white screen
android·java·uni-app
摸鱼仙人~8 小时前
从 Gunicorn 到 FastAPI:Python Web 生产环境架构演进与实战指南
python·fastapi·gunicorn
難釋懷8 小时前
解决状态登录刷新问题
java·开发语言·javascript
潇凝子潇8 小时前
Java 设计支持动态调整的LFU缓存: 需包含热度衰减曲线和淘汰策略监控
java·spring·缓存
94甘蓝8 小时前
第 5 篇 Spring AI - Tool Calling 全面解析:从基础到高级应用
java·人工智能·函数调用·工具调用·spring ai·tool calling
毕设源码-朱学姐8 小时前
【开题答辩全过程】以 基于Django框架中山社区社会补助系统为例,包含答辩的问题和答案
后端·python·django
醉舞经阁半卷书18 小时前
Matplotlib从入门到精通
python·数据分析·matplotlib
历程里程碑8 小时前
Linux 5 目录权限与粘滞位详解
linux·运维·服务器·数据结构·python·算法·tornado
酉鬼女又兒8 小时前
SQL113+114 更新记录(一)(二)+更新数据知识总结
java·服务器·前端
程序员哈基耄9 小时前
安全高效,本地运行:全能文件格式转换工具
大数据·python·安全