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) {
        //
    }
}
相关推荐
小趴蔡ha1 天前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534781 天前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
mifengxing1 天前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
数字化转型分享点滴1 天前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03011 天前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比1 天前
(开源项目)x-claw(总)
python·ai·rust·开源
xrandzj1 天前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
markinmarkin1 天前
Spring 中Bean 的作用域有哪些?
java·后端·spring
山荷枝1 天前
Java学习第十天
java·学习
matlabgoodboy1 天前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计