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) {
        //
    }
}
相关推荐
卷无止境3 小时前
Python能做嵌入式开发吗?一份写给动手派的生态与硬件全景图
后端·python
月光船幽幽7 小时前
检测用户意图复杂性的关键方法
人工智能·python
疯狂打码的少年7 小时前
【数据库技术】关系模型基本概念(关系/属性/元组/键)
java·服务器·数据库·笔记
Mr数据杨9 小时前
【Codex】用学生入学评估模块建立新生能力画像
android·java·javascript·django·codex·项目开发
2601_962056239 小时前
Spring Boot 入门 与 无法解析符号 springframework 的解决
java·spring boot·后端
Thomas214310 小时前
Java scala 数组 链表
java·链表·scala
威联通网络存储10 小时前
TS-h3087XU-RP 汽车零部件质检追溯部署
python·汽车
亚历克斯神10 小时前
低代码与 AI 的融合趋势——从可视化搭建到自然语言生成应用
java·spring·微服务
你驴我10 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
IT毕设实战小研10 小时前
基于安卓的空气质量查询系统
android·大数据·vue.js·爬虫·python·django·课程设计