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) {
        //
    }
}
相关推荐
m0_747854521 分钟前
MySQL如何缓解热点数据的更新瓶颈_合并更新请求与排队控制
jvm·数据库·python
zhangchaoxies2 分钟前
React Flow 边缘丢失与错位问题的根源及 Hooks 重构方案
jvm·数据库·python
Wyz201210242 分钟前
如何在 React 中正确绑定 onClick 事件避免字符串赋值错误
jvm·数据库·python
m0_3776182310 分钟前
如何在 Node.js 服务器间正确配置 CORS 实现跨子域资源访问
jvm·数据库·python
qq_1898070311 分钟前
如何在 Django ListView 中正确过滤当前用户的照片数据
jvm·数据库·python
老约家的可汗12 分钟前
搜索二叉树的概念及使用
java·开发语言
m0_3776182312 分钟前
Go语言如何用systemd_Go语言systemd服务管理教程【总结】
jvm·数据库·python
棉猴16 分钟前
python海龟绘图之计算夹角towards()
开发语言·python·turtle·海龟绘图·towards
星马梦缘22 分钟前
强化学习实战8.1——用PPO打赢星际争霸【环境配置与下位机代码】
人工智能·python·jupyter·强化学习·星际争霸·stablebaseline3·starcraft2
qq_1898070323 分钟前
SQL快速查找分组记录数异常的分类_利用HAVING筛选
jvm·数据库·python