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) {
        //
    }
}
相关推荐
wifi___2 小时前
全局异常处理的原理
java·开发语言
青 春 记 忆6 小时前
零基础入门Python11|Git实战:为任务管理器建立版本历史
开发语言·git·vscode·python·python3.11
Python私教6 小时前
多个项目怎么安全合并?先适配,再切换
后端·python·架构
2601_963870207 小时前
【计算机毕业设计】基于Spring Boot的专科医院医疗管理系统
java·spring boot·课程设计
Bingo_BIG7 小时前
Java Spring 批量修改,实体、接口、方法的定义
java·spring
画中有画7 小时前
软件架构中质量属性(性能、安全、可扩展性)的权衡设计
java·运维·安全
Shaoxi Zhang8 小时前
JAVA学习笔记035——对象和JSON格式
java·笔记·学习
赵丙双8 小时前
CountDownLatch 源码分析
java·aqs·countdownlatch
余额瞒着我当琳8 小时前
C++--深拷贝三件套 + swap + 写时拷贝 + vector 扩容 + reserve
java·开发语言·c++
thefool1122668 小时前
翻转二叉树
java