zoukankan      html  css  js  c++  java
  • MongoDB:实体对象(javabean)转DBObject

    代码仅供练习(反射,泛型):

    package utils;
    import java.lang.reflect.Field;
    import com.mongodb.BasicDBObject;
    import com.mongodb.DBObject;
    import pojo.User;
    public class BeanFromDBObject {
        /**
         * @Description:bean-->DBObject
         * @param  bean
         * @return DBObject 返回类型
         */
        public static <T> DBObject getDBObject(T bean) {
            if (bean == null) {
                return null;
            }
            DBObject obj = new BasicDBObject();
            Field[] field = bean.getClass().getDeclaredFields();
            for (Field f : field) {
                String name = f.getName();
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                try {
                    Object oj = f.get(bean);
                    if (oj == null) {
                        obj.put(name, "");
                    } else if (oj instanceof Integer) {
                        int value = ((Integer) oj).intValue();
                        obj.put(name, value);
                    } else if (oj instanceof Double) {
                        Double value = ((Double) oj).doubleValue();
                        obj.put(name, value);
                    } else if (oj instanceof Float) {
                        Float value = ((Float) oj).floatValue();
                        obj.put(name, value);
                    } else if (oj instanceof Boolean) {
                        Boolean value = ((Boolean) oj).booleanValue();
                        obj.put(name, value);
                    } else if (oj instanceof Long) {
                        Long value = ((Long) oj).longValue();
                        obj.put(name, value);
                    } else {
                        obj.put(name, oj);
                    }
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
            }
            return obj;
    
        }
    }
  • 相关阅读:
    Getting Started with ASP.NET Web API 2 (C#)
    借助StackView简化页面布局
    获取网络数据
    歌曲列表和频道列表
    自定义UIImage组件实现圆形封面,转动,以及模糊背景
    什么是CoreData?
    Swift
    PNChart图表绘制库的使用
    PathCover个人主页控件使用
    ProgressHUD进程提示控件的使用
  • 原文地址:https://www.cnblogs.com/byteworld/p/5924626.html
Copyright © 2011-2022 走看看