|
20 | 20 | import org.junit.Test; |
21 | 21 |
|
22 | 22 | import java.lang.reflect.Type; |
| 23 | +import java.util.Map; |
23 | 24 | import java.util.concurrent.atomic.AtomicInteger; |
24 | 25 |
|
25 | 26 | import static org.junit.Assert.assertEquals; |
26 | 27 |
|
| 28 | +import android.util.ArrayMap; |
| 29 | + |
27 | 30 | public class TypeAdapterTest { |
28 | 31 |
|
29 | 32 | @Test |
@@ -68,4 +71,55 @@ public TypeAdapter<?> create(QuickJS quickJS, Type type) { |
68 | 71 | return null; |
69 | 72 | } |
70 | 73 | } |
| 74 | + |
| 75 | + @Test |
| 76 | + public void registerMapAdapter() { |
| 77 | + Type mapType = new JavaType<Map<String, String>>() {}.type; |
| 78 | + |
| 79 | + QuickJS quickJS = new QuickJS.Builder() |
| 80 | + .registerTypeAdapter(mapType, new MapTypeAdapter().nullable()) |
| 81 | + .build(); |
| 82 | + try (JSRuntime runtime = quickJS.createJSRuntime()) { |
| 83 | + try (JSContext context = runtime.createJSContext()) { |
| 84 | + Map<String, String> actual = context.evaluate( |
| 85 | + "a = { key1: \"value1\", key2: \"value2\" }", "test.js", mapType); |
| 86 | + Map<String, String> expected = new ArrayMap<>(); |
| 87 | + expected.put("key1", "value1"); |
| 88 | + expected.put("key2", "value2"); |
| 89 | + assertEquals(expected, actual); |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private static class MapTypeAdapter extends TypeAdapter<Map<String, String>> { |
| 95 | + @Override |
| 96 | + public JSValue toJSValue(JSContext context, Map<String, String> value) { |
| 97 | + JSObject jo = context.createJSObject(); |
| 98 | + value.forEach((k, v) -> { |
| 99 | + if (k == null) return; |
| 100 | + jo.setProperty(k, context.createJSString(v)); |
| 101 | + }); |
| 102 | + return jo; |
| 103 | + } |
| 104 | + |
| 105 | + @Override |
| 106 | + public Map<String, String> fromJSValue(JSContext context, JSValue value) { |
| 107 | + JSObject jo = value.cast(JSObject.class); |
| 108 | + JSFunction keysFunction = context.getGlobalObject() |
| 109 | + .getProperty("Object").cast(JSObject.class) |
| 110 | + .getProperty("keys").cast(JSFunction.class); |
| 111 | + |
| 112 | + TypeAdapter<String[]> adapter = context.quickJS.getAdapter(String[].class); |
| 113 | + JSValue keysResult = keysFunction.invoke(null, new JSValue[] { jo }); |
| 114 | + String[] keys = adapter.fromJSValue(context, keysResult); |
| 115 | + |
| 116 | + Map<String, String> map = new ArrayMap<>(keys.length); |
| 117 | + for (String key: keys) { |
| 118 | + String val = jo.getProperty(key).cast(JSString.class).getString(); |
| 119 | + map.put(key, val); |
| 120 | + } |
| 121 | + |
| 122 | + return map; |
| 123 | + } |
| 124 | + } |
71 | 125 | } |
0 commit comments