java调用未知类的指定方法简单实例

时间:2022-06-30 22:03:50

代码如下:


    /**
     * 获取任意对象里面的returnMapObject的值.并且组成list
     * @param <T>
     * @param list
     * @param fields
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static <T> List<Map<String,Object>> returnMapList(List<T> list,String ...fields) throws Exception{
        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        if(list == null || list.isEmpty())return mapList;
        for(T t : list){
            Method m = t.getClass().getMethod("returnMapObject",fields.getClass());
            Object result = m.invoke(t,(Object)fields);
            mapList.add((Map<String, Object>) result);
        }
        return mapList;
    }