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 小时前
Python 综合项目实战:学生成绩管理系统(命令行版)
后端·python·ipython
Brsentibi1 小时前
基于python代码自动生成关于建筑安全检测的报告
python·microsoft
程序员爱钓鱼1 小时前
REST API 与前后端交互:让应用真正跑起来
后端·python·ipython
敏姐的后花园1 小时前
模考倒计时网页版
java·服务器·前端
gCode Teacher 格码致知3 小时前
Python基础教学:Python的openpyxl和python-docx模块结合Excel和Word模板进行数据写入-由Deepseek产生
python·excel
Dcs3 小时前
Java 中 UnaryOperator 接口与 Lambda 表达式的应用示例
java·后端
Destiny_where5 小时前
Agent平台-RAGFlow(2)-源码安装
python·ai
bagadesu5 小时前
使用Docker构建Node.js应用的详细指南
java·后端
没有bug.的程序员5 小时前
Spring Cloud Gateway 性能优化与限流设计
java·spring boot·spring·nacos·性能优化·gateway·springcloud