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) {
        //
    }
}
相关推荐
点云-激光雷达-Slam-三维牙齿31 分钟前
速度起飞 笔记本电脑6G显卡llama运行Qwen3.6 35BA3B MTP 大模型
人工智能·python·电脑·llama
言乐61 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
xbgRS1 小时前
springboot的自动装配
java·spring boot
从零开始学习人工智能8 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
嘻哈∠※8 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
卷无止境9 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha13149 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教9 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
白狐_7989 小时前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
Python私教10 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi