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) {
        //
    }
}
相关推荐
godspeed_lucip1 分钟前
LLM和Agent——专题3: Agentic Workflow 入门(4)
人工智能·python
godspeed_lucip4 分钟前
LLM和Agent——专题3: Agentic Workflow 入门(2)
网络·人工智能·python
mingshili6 分钟前
[Python] Python中自带模块级的单例模式-不需要定义单例类
python·单例模式
asdfg12589639 分钟前
Java中的Comparator 和JS中的回调函数好相似
java·开发语言
会编程的土豆15 分钟前
消息队列(MQ)入门笔记
java·笔记·spring
专注VB编程开发20年21 分钟前
python运行提速方案全解
java·linux·服务器
涤生大数据25 分钟前
大数据面试高频题:row_number() 数据倾斜到底怎么解决?
java·大数据·面试
weixin_4467291625 分钟前
注解和反射
java·开发语言
alphaTao27 分钟前
LeetCode 每日一题 2026/5/18-2026/5/24
python·leetcode
徐安安_ye128 分钟前
FlashAttention学习路线:从调API到写算子,你该走哪条路
python·学习