|
1 | 1 | package net.discordjug.javabot.data.config; |
2 | 2 |
|
| 3 | +import com.google.gson.Gson; |
| 4 | +import com.google.gson.GsonBuilder; |
3 | 5 | import lombok.extern.slf4j.Slf4j; |
4 | 6 | import net.discordjug.javabot.util.ExceptionLogger; |
5 | 7 | import net.discordjug.javabot.util.Pair; |
|
14 | 16 | import java.util.Map; |
15 | 17 | import java.util.Optional; |
16 | 18 | import java.util.function.Function; |
| 19 | +import java.util.regex.Pattern; |
17 | 20 |
|
18 | 21 | /** |
19 | 22 | * Utility class for resolving JSON files. |
20 | 23 | */ |
21 | 24 | @Slf4j |
22 | 25 | public class ReflectionUtils { |
23 | 26 | private static final Map<Class<?>, Function<String, Object>> propertyTypeParsers = new HashMap<>(); |
| 27 | + private static final Gson gson = new GsonBuilder() |
| 28 | + .serializeNulls() |
| 29 | + .setPrettyPrinting() |
| 30 | + .registerTypeAdapter(Pattern.class, new PatternTypeAdapter()) |
| 31 | + .create(); |
24 | 32 |
|
25 | 33 | static { |
26 | 34 | propertyTypeParsers.put(Integer.class, Integer::parseInt); |
@@ -126,13 +134,11 @@ private static Field findDeclaredField(Class<?> cl, String name) throws NoSuchFi |
126 | 134 | * @param field The field to set. |
127 | 135 | * @param parent The object whose property value to set. |
128 | 136 | * @param s The string representation of the value. |
| 137 | + * @return Returns the edited {@link Field}. |
129 | 138 | * @throws IllegalAccessException If the field cannot be set. |
130 | 139 | */ |
131 | | - public static void set(@NotNull Field field, @NotNull Object parent, @NotNull String s) throws IllegalAccessException { |
132 | | - Function<String, Object> parser = propertyTypeParsers.get(field.getType()); |
133 | | - if (parser == null) { |
134 | | - throw new IllegalArgumentException("No supported property type parser for the type " + field.getType().getSimpleName()); |
135 | | - } |
136 | | - field.set(parent, parser.apply(s)); |
| 140 | + public static Field set(@NotNull Field field, @NotNull Object parent, @NotNull String s) throws IllegalAccessException { |
| 141 | + field.set(parent, gson.fromJson(s, field.getType())); |
| 142 | + return field; |
137 | 143 | } |
138 | 144 | } |
0 commit comments