JAVA对象和BSON⽂档对象之间的相互转换⽀持 列表,哈希,数组和基本类型
import flect.Array;
import flect.Field;
import flect.Modifier;
import flect.ParameterizedType;
import flect.TypeVariable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.annotation.Transient;
public class BsonUtil {
private static Logger logger = Logger(BsonUtil.class);
public static <T> List<T> toBeans(List<Document> documents, Class<T> clazz){
List<T> list = new ArrayList<T>();
for (int i = 0; null != documents && i < documents.size(); i++) {
list.add((i), clazz));
}
return list;
}
@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
public static <T> T toBean(Document document,Class<T> clazz) {
T entity = null;
try {
entity = (wInstance();
Field[] fields = DeclaredFields();
for (Field field : fields) {
if(Modifier.Modifiers())) {
continue;//静态成员不转换
}
field.setAccessible(true);
Class fieldClazz = Type();
String key = Name();
if("id".equals(key)) {
key = "_id";
}
Object value = null;
try {
value = (entity);
} catch (Exception e) {
e.printStackTrace();
}
Object val = (key);
if(val == null) {
continue;
}
if(isPrimitive(fieldClazz) || fieldClazz == String.class) {
if(field!=null) field.set(entity, val);
continue;
}
//数组
if(fieldClazz.isArray()) {
String itemClazzName = TypeName().substring(0, TypeName().length()-2);
Class itemClazz = null;
try {
itemClazz = Class.forName(itemClazzName);
itemClazz = Class.forName(itemClazzName);
} catch (ClassNotFoundException e) {
//此时为基本类型
itemClazz = toPrimitiveClass(itemClazzName);
}
Object array = (key),itemClazz);
if(field!=null) field.set(entity, array);
continue;
}
//列表
if (List.class.isAssignableFrom(fieldClazz)) {
ParameterizedType fc = (GenericType();
TypeVariable[] types = TypeParameters();
List list = (List)value;
if(value == null) {
list = new ArrayList<>();
if(field!=null) field.set(entity, list);
}
(key), list, (ActualTypeArguments()[0]);
continue;
}
//哈希表
if(Map.class.isAssignableFrom(fieldClazz)) {
ParameterizedType fc = (GenericType();
Map map = (Map) value;
if(value == null) {
map = new HashMap<>();
if(field!=null) field.set(entity, map);
}
(key), map, (ActualTypeArguments()[0],(ActualTypeArguments()[1]);                    continue;
}
document.put(key, toBean((Document)val, fieldClazz));
}
} catch (Exception e) {
<("toBean() error , clazz:"+Name(), e);
}
return entity;
}
/**
* 转换成适合update语句的Document对象
* @param entity
* @return
*/
public static Document toDocumentForUpdate(Object entity) {
Document document = new Document();
document.put("$set", toDocument(entity));
return document;
}
/**
* 转换成Document
* @param entity
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Document toDocument(Object entity) {
if(entity == null) {
return null;
}
Document document = new Document();
Class clazz = Class();
Field[] fields = DeclaredFields();
for (Field field : fields) {
if(Modifier.Modifiers())) {
continue;//静态成员不转换
}
field.setAccessible(true);
Class fieldClazz = Type();
AnnotationsByType(Transient.class).length>0) {
AnnotationsByType(Transient.class).length>0) {
//@Transient 标识的属性不进⾏转换
continue;
}
String key = Name();
if("id".equals(key)) {
key = "_id";
}
Object value = null;
try {
value = (entity);
} catch (Exception e) {
e.printStackTrace();
}
if(value == null) {
continue;
}
try {
if(isPrimitive(fieldClazz) || fieldClazz == String.class) {
document.put(key, value);
continue;
}
if(fieldClazz.isArray()) { //数组
String itemClazzName = TypeName().substring(0, TypeName().length()-2);                    Class itemClazz = null;
try {
itemClazz = Class.forName(itemClazzName);
} catch (ClassNotFoundException e) {
//此时为基本类型
itemClazz = toPrimitiveClass(itemClazzName);
}
int len = Length(value);
if(isPrimitive(itemClazz) || itemClazz == String.class) {
List values = new ArrayList<>();
for(int i=0;i<len;i++) {
Object object = (value, i);
values.add(object);
}
document.put(key, values);
}else {
List<Document> listDocument = new ArrayList<>();
document.put(key, listDocument);
for(int i=0;i<len;i++) {
Object object = (value, i);
listDocument.add(toDocument(object));
}
}
continue;
}
/
/列表
if (List.class.isAssignableFrom(fieldClazz)) {
List list = (List)value;
ParameterizedType fc = (GenericType();
Class itemClazz = (ActualTypeArguments()[0];
if(isPrimitive(itemClazz) || itemClazz == String.class) {
List values = new ArrayList<>();
for (Object object : list) {
values.add(object);
}
document.put(key, values);
}else {
List<Document> listDocument = new ArrayList<>();
document.put(key, listDocument);
for (Object object : list) {
listDocument.add(toDocument(object));
listDocument.add(toDocument(object));
}
}
continue;
}
//哈希表
if (Map.class.isAssignableFrom(fieldClazz)) {
Map map = ((entity);
Set<Map.Entry> entries = Set();
Map mpperMap = new HashMap<>();
document.put(key, mpperMap);
ParameterizedType fc = (GenericType();
Class keyClazz = (ActualTypeArguments()[0];
if(keyClazz != String.class && !isPrimitive(keyClazz)) {
throw new RuntimeException("不⽀持的Map,转换成document的key只能为基本类型或字符串");
}
Class itemClazz = (ActualTypeArguments()[1];
if(itemClazz == String.class || isPrimitive(itemClazz)) {
for (Map.Entry entry : entries) {
mpperMap.Key().toString(), Value());
}
}else {
for (Map.Entry entry : entries) {
mpperMap.Key().toString(), Value()));
}
}
//                  Document mapDocument = new Document();
//                  document.put(key, mapDocument);
/
/
//                  for (Map.Entry entry : entries) {
//                      Object object = Value();
//                      if(Class()) || Class() == String.class) {
//                          mapDocument.Key().toString(), object);
//                      }else {
//                          mapDocument.Key().toString(), toDocument(object));
//                      }
//                  }
continue;
}
document.put(key, toDocument(value));
}catch (Exception e) {
<("toDocument() , error clazz="+Class().getName(),e);
}
}
return document;
}
@SuppressWarnings("rawtypes")
private static boolean isPrimitive(Class clazz) {
if(clazz.isPrimitive()) {
return true;
}
if(Long.class == clazz || Integer.class == clazz || Double.class == clazz || Float.class == clazz || Short.class == clazz || Boolean.class == clazz) {            return true;
}
return false;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object toArray(Object value, Class itemClazz) {
List list = (List)value;
Object array = wInstance(itemClazz, list.size());
int i = 0;
for (Object object : list) {
if(object instanceof Document) {
Array.set(array, i++, toBean((Document)object,itemClazz));
}else {
Array.set(array, i++, object);
}
}
}
return array;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void toMap(Object value , Map map,Class keyClazz,Class itemClazz) throws Instantiati
onException, IllegalAccessException {        Set<Map.Entry> entries = ((Map)value).entrySet();
for (Map.Entry entry : entries) {
Object keyV = Key().getClass() == String.class ? Key() : Key().toString(), keyClazz);
Object itemV = Value();
if(itemV instanceof Document) {
map.put(keyV, toBean((Document)itemV,itemClazz));
}else {
map.put(keyV,itemV);
}
}
//      Document document = (Document) value;
//      for (Map.Entry entry : Set()) {
//          Object keyV = Key().toString(), keyClazz);
//          Object itemV = (Key());
//
//          if(itemV instanceof Document) {
//              map.put(keyV, toBean((Document)itemV,itemClazz));
//          }else {
//              map.put(keyV,itemV);
//          }
//
//      }
}
@SuppressWarnings("rawtypes")
private static Object toPrimitive(String value,Class clazz) {
if(int.class == clazz || Integer.class == clazz) {
return Integer.valueOf(value);
}else if(long.class == clazz || Long.class == clazz) {
return Long.valueOf(value);
}else if(short.class == clazz || Short.class == clazz) {
return Short.valueOf(value);
}else if(double.class == clazz || Double.class == clazz) {
return Double.valueOf(value);
}else if(float.class == clazz || Float.class == clazz) {
return Float.valueOf(value);
}else if(boolean.class == clazz || Boolean.class == clazz) {
return Boolean.valueOf(value);
}else {
throw new RuntimeException("Map key nonsupport ");
}
}
@SuppressWarnings("rawtypes")
private static Class toPrimitiveClass(String primitiveClazzName) {
Class itemClazz = null;
/
/此时为基本类型
if("long".equals(primitiveClazzName)) {
object to
itemClazz = long.class;
}else if("int".equals(primitiveClazzName)) {
itemClazz = int.class;
}else if("short".equals(primitiveClazzName)) {
itemClazz = short.class;
}else if("double".equals(primitiveClazzName)) {
itemClazz = double.class;
}else if("float".equals(primitiveClazzName)) {
itemClazz = float.class;
}else if("boolean".equals(primitiveClazzName)) {
itemClazz = boolean.class;
}else {
throw new RuntimeException("nonsupport type ");
}
return itemClazz;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void toList(Object value , List list,Class itemClazz) throws InstantiationException, IllegalAccessException {
Class() == Document[].class) {
Document[] documents = (Document[])value;
for (Document document : documents) {

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。