| 69 | /// are never persisted, so the renaming has no observable effect on |
| 70 | /// behavior. |
| 71 | public final class Mappers { |
| 72 | |
| 73 | private static final Map<String, Mapper<?>> BY_NAME = new HashMap<String, Mapper<?>>(); |
| 74 | |
| 75 | private Mappers() { |
| 76 | } |
| 77 | |
| 78 | /// Installs `mapper` under `mapper.type().getName()`. The generated |
| 79 | /// per-class mapper's static initializer calls this; hand-written |
| 80 | /// mappers for classes outside the build's annotation scan call it |
| 81 | /// explicitly. |
| 82 | public static <T> void register(Mapper<T> mapper) { |
| 83 | if (mapper == null) { |
| 84 | throw new IllegalArgumentException("mapper is null"); |
| 85 | } |
| 86 | BY_NAME.put(mapper.type().getName(), mapper); |
| 87 | } |
| 88 | |
| 89 | /// Looks up the mapper for `type` (by `type.getName()`) or null when |
| 90 | /// none is registered. |
| 91 | @SuppressWarnings("unchecked") |
| 92 | public static <T> Mapper<T> get(Class<T> type) { |
| 93 | if (type == null) { |
| 94 | return null; |
| 95 | } |
| 96 | return (Mapper<T>) BY_NAME.get(type.getName()); |
| 97 | } |
| 98 | |
| 99 | /// Serializes `instance` to JSON. Throws `IllegalStateException` when |
| 100 | /// no mapper is registered for its concrete class; that always points |
| 101 | /// at a missing `@Mapped` annotation or a build that ran without the |
| 102 | /// process-annotations Mojo. |
| 103 | public static String toJson(Object instance) { |
| 104 | if (instance == null) { |
| 105 | return "null"; |
| 106 | } |
| 107 | @SuppressWarnings("unchecked") |
| 108 | Mapper<Object> m = (Mapper<Object>) BY_NAME.get(instance.getClass().getName()); |
| 109 | if (m == null) { |
| 110 | throw missing(instance.getClass()); |
| 111 | } |
| 112 | Map<String, Object> root = m.toMap(instance); |
| 113 | StringBuilder sb = new StringBuilder(); |
| 114 | writeJson(sb, root); |
| 115 | return sb.toString(); |
| 116 | } |
| 117 | |
| 118 | /// Inverse of `#toJson`. Parses the JSON text and hands the resulting |
| 119 | /// Map to the registered mapper. |
| 120 | public static <T> T fromJson(String json, Class<T> type) { |
| 121 | if (json == null) { |
| 122 | return null; |
| 123 | } |
| 124 | Mapper<T> m = get(type); |
| 125 | if (m == null) { |
| 126 | throw missing(type); |
| 127 | } |
| 128 | try { |
nothing calls this directly
no outgoing calls
no test coverage detected