|
2 | 2 |
|
3 | 3 | import com.google.gson.JsonElement; |
4 | 4 | import com.google.gson.JsonObject; |
5 | | -import com.google.gson.JsonParser; |
6 | 5 |
|
| 6 | +import java.lang.reflect.Field; |
7 | 7 | import java.util.Map; |
8 | 8 |
|
9 | | -// SuperEntry is used as the common class that caould be consumed by Entry and Query |
10 | | -public class SuperEntry { |
11 | | - |
| 9 | +public class Utils { |
12 | 10 |
|
13 | 11 | /** |
14 | 12 | * Merge "source" into "target". If fields have equal name, merge them recursively. Null values in source will |
@@ -43,15 +41,24 @@ public static JsonObject deepMerge(JsonObject source, JsonObject target) { |
43 | 41 | } |
44 | 42 |
|
45 | 43 |
|
46 | | - /** |
47 | | - * simple test |
48 | | - */ |
49 | | - public static void main(String[] args) { |
50 | | - JsonParser parser = new JsonParser(); |
51 | | - JsonObject sourse = parser.parse("{offer: {issue1: null, issue2: null}, accept: true, reject: null}").getAsJsonObject(); |
52 | | - JsonObject target = parser.parse("{offer: {issue2: value2}, reject: false}").getAsJsonObject(); |
53 | | - System.out.println(deepMerge(sourse, target)); |
| 44 | + public <T> T merge(T local, T remote) throws IllegalAccessException, InstantiationException { |
| 45 | + Class<?> clazz = local.getClass(); |
| 46 | + Object merged = clazz.newInstance(); |
| 47 | + for (Field field : clazz.getDeclaredFields()) { |
| 48 | + field.setAccessible(true); |
| 49 | + Object localValue = field.get(local); |
| 50 | + Object remoteValue = field.get(remote); |
| 51 | + if (localValue != null) { |
| 52 | + switch (localValue.getClass().getSimpleName()) { |
| 53 | + case "Default": |
| 54 | + case "Detail": |
| 55 | + field.set(merged, this.merge(localValue, remoteValue)); |
| 56 | + break; |
| 57 | + default: |
| 58 | + field.set(merged, (remoteValue != null) ? remoteValue : localValue); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + return (T) merged; |
54 | 63 | } |
55 | | - |
56 | | - |
57 | 64 | } |
0 commit comments