Java的Method


1.傳入一個List對象,及該對象的屬性名獲取該List中所有該屬性的值(屬性類型為String)

private static List<String> getWybsListValueByName(String fieldName, List list) {
        try {
            List<String>lists=new ArrayList<>(list.size());
            for (Object object:list) {
                String firstCode = fieldName.substring(0, 1).toUpperCase();
                String getter = "get" + firstCode + fieldName.substring(1);
                Method method = object.getClass().getMethod(getter);
                Object value = method.invoke(object);
                lists.add(value.toString());
            }
            return lists;
        } catch (Exception e) {
            return null;
        }
    }

 獲取某個對象全部屬性及屬性值映射成map

    public static Map getDataList(test test,Object o) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Map<String,Object>map=new HashMap<>();
        Field[] declaredFields = o.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            String s = declaredField.toGenericString();
            while (s.contains(".")) {
                s = s.substring(s.indexOf(".") + 1);
            }
            String name=s;
            //get方法list
            s = "get" + s.substring(0, 1).toUpperCase() + s.substring(1);
            Object value = o.getClass().getMethod(s).invoke(o);
            map.put(name,value);
        }
        System.out.println("result ======"+map);
        return map;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM