The code is for practice only (reflection, generics):
PackageUtils;ImportJava.lang.reflect.Field;ImportCom.mongodb.BasicDBObject;ImportCom.mongodb.DBObject;ImportPojo. User; Public classBeanfromdbobject {/*** @Description: Bean-->dbobject *@paramBean *@returndbobject return type*/ Public Static<T>dbobject getdbobject (T Bean) {if(Bean = =NULL) { return NULL; } dbobject obj=NewBasicdbobject (); 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(OJinstanceofInteger) { intValue =((Integer) OJ). Intvalue (); Obj.put (name, value); } Else if(OJinstanceofDouble) {Double value=((Double) OJ). Doublevalue (); Obj.put (name, value); } Else if(OJinstanceofFloat) {Float value=((Float) OJ). Floatvalue (); Obj.put (name, value); } Else if(OJinstanceofBoolean) {Boolean value=((Boolean) OJ). Booleanvalue (); Obj.put (name, value); } Else if(OJinstanceofLong) {Long value=((Long) OJ). Longvalue (); Obj.put (name, value); } Else{obj.put (name, OJ); } } Catch(Exception e) {e.printstacktrace (); } } returnobj; }}
MongoDB: Entity object (JavaBean) goto DBObject