The
looks like this:
Package com.iqbon.spider.util;
Import Java.lang.reflect.Field;
Import java.lang.reflect.InvocationTargetException;
Import Java.util.Date;
Import Org.apache.commons.beanutils.BeanUtils;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DBObject; public class Beanutil {/** * Converts entity bean objects to DBObject * @param bean * @return * @throws illegalargumentexcept Ion * @throws Illegalaccessexception */public static <T> dbobject bean2dbobject (T Bean) throws Illegalargum
Entexception, Illegalaccessexception {if (bean = = null) {return null;
} dbobject dbobject = new Basicdbobject ();
Gets all the property fields in the corresponding class of the object field[] fields = Bean.getclass (). Getdeclaredfields ();
for (Field field:fields) {//Get property name String VarName = Field.getname ();
Modify access control permissions Boolean accessflag = Field.isaccessible ();
if (!accessflag) {field.setaccessible (true);
Object param = field.get (bean); if (param = = null) {continue;
else if (param instanceof Integer) {//the type int value = ((Integer) param) of the variable. intvalue ();
Dbobject.put (varName, value);
else if (param instanceof string) {String value = (string) param;
Dbobject.put (varName, value);
else if (param instanceof Double) {Double value = (double) param). Doublevalue ();
Dbobject.put (varName, value);
else if (param instanceof float) {Float value = ((Float) param). Floatvalue ();
Dbobject.put (varName, value);
else if (param instanceof long) {Long value = ((Long) param). Longvalue ();
Dbobject.put (varName, value);
else if (param instanceof Boolean) {Boolean value = ((Boolean) param). Booleanvalue ();
Dbobject.put (varName, value);
else if (param instanceof date) {Date value = (date) param;
Dbobject.put (varName, value);
}//restore access Control permissions field.setaccessible (Accessflag);
return dbobject; /** * Converts dbobject to bean object * @param dbobjECT * @param bean * @return * @throws illegalaccessexception * @throws invocationtargetexception * @throws Nosuchmethodexception */public static <T> T Dbobject2bean (dbobject dbobject, T Bean) throws ILLEGALACCESSEXCEP
tion, invocationtargetexception, nosuchmethodexception {if (bean = = null) {return null;
} field[] fields = Bean.getclass (). Getdeclaredfields ();
for (Field field:fields) {String varName = Field.getname ();
Object object = Dbobject.get (VarName);
if (object!= null) {Beanutils.setproperty (bean, VarName, object);
} return bean; }
}
The above is a small series for you to bring Java operations MongoDB, object Bean and DBObject Mutual Conversion method (recommended) All content, I hope that we support cloud-Habitat Community ~