Java 获取实体类对象的属性与值 2018-06-28

Object bean为实体对象.


public static String getBody(Object bean) {

    Class classi= bean.getClass();

    Field[] field= classi.getDeclaredFields();

    StringBuilder stb= new StringBuilder();

    for (int i= 0; i< field.length; i++) {

        Field f= field[i];

        f.setAccessible(true);

        String key= f.getName();

        Object obj= null;

        try {

            obj= f.get(bean);

            Map map= new HashMap<>();

            map.put(key, obj+ "");

            Map map1= sortMapByKey(map);

            for (Map.Entry entry : map1.entrySet()) {

                    stb.append(entry.getKey() + "=" + entry.getValue() + "&");

}

        } catch (IllegalAccessException e) {

            e.printStackTrace();

}

}

    Logy.d(stb.toString());

    return stb.toString();

}

/**

* 使用 Map按key进行排序

*

* @parammap

* @return

*/

public static Map sortMapByKey(Map map) {

    if (map== null || map.isEmpty()) {

        return null;

}

    Map sortMap= new TreeMap(

            new MapKeyComparator());

    sortMap.putAll(map);

    return sortMap;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,839评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,269评论 19 139
  • 姓名:冉乔琪~公司:天兴医药 【日精进打卡第※160※天】 【知~学习】 《六项精进》2遍 共360遍 《大学》2...
    小小新酱阅读 194评论 0 0
  • 这其实是2013年写的一些碎片文字,那时候重温这个版本的《倚天屠龙记》,断断续续写了一些自己的感受,重新整理如下。...
    夜猫杂俎阅读 2,161评论 2 4