Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static <T> BasicDBObject asDBObject(T instance) {
- BasicDBObject b = new BasicDBObject();
- Collection<Field> fieldMap = getAnnotationFields(instance.getClass(), DBSync.class);
- for (Field f : fieldMap) {
- try {
- DBSync saveData = f.getAnnotation(DBSync.class);
- if (saveData == null) {
- continue;
- }
- if (!isSerializeAble(f)) {
- continue;
- }
- boolean hadAccess = f.isAccessible();
- if (!hadAccess) {
- f.setAccessible(true);
- }
- String fieldName = f.getName();
- if (!saveData.value().isEmpty()) {
- fieldName = saveData.value();
- }
- if (f.getType().isArray()) { // array
- Object[] arrayData = (Object[]) f.get(instance);
- Class<?> arrayType = getArrayType(f);
- if (isPrimitive(arrayType)) {
- b.put(fieldName, f.get(instance));
- continue;
- } else {
- BasicDBList list = new BasicDBList();
- for (Object arrayObject : arrayData) {
- list.add(asDBObject(arrayObject));
- }
- b.put(fieldName, list);
- continue;
- }
- } else if (Collection.class.isAssignableFrom(f.getType())) { // Collection
- Collection collectionData = (Collection) f.get(instance);
- Class<?> collectionType = getCollectionType(f);
- if (isPrimitive(collectionType)) {
- b.put(fieldName, f.get(instance));
- continue;
- } else {
- BasicDBList list = new BasicDBList();
- for (Object collectionObject : collectionData) {
- list.add(asDBObject(collectionObject));
- }
- b.put(fieldName, list);
- continue;
- }
- }
- Object o = f.get(instance);
- f.setAccessible(hadAccess);
- b.put(fieldName, o);
- } catch (IllegalAccessException | IllegalArgumentException ex) {
- ex.printStackTrace();
- }
- }
- return b;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement