1 package org.djutils.data.serialization;
2
3 import java.lang.reflect.InvocationTargetException;
4 import java.lang.reflect.Method;
5 import java.util.LinkedHashMap;
6 import java.util.Map;
7
8 import org.djunits.unit.Unit;
9 import org.djunits.value.vdouble.scalar.base.DoubleScalar;
10
11
12
13
14
15
16
17
18
19
20
21
22
23 public class DoubleScalarSerializer<U extends Unit<U>, S extends DoubleScalar<U, S>> implements TextSerializer<S>
24 {
25
26 private static Map<String, Method> valueOfMethodCache = new LinkedHashMap<>();
27
28
29 private static Map<String, Unit<?>> unitCache = new LinkedHashMap<>();
30
31
32
33
34
35
36 @SuppressWarnings("unchecked")
37 @Override
38 public String serialize(final S value, final String unitString)
39 {
40 if (value == null)
41 {
42 return null;
43 }
44
45 String key = value.getClass().getSimpleName() + "_" + unitString;
46 Unit<?> unit = unitCache.get(key);
47 if (unit == null)
48 {
49 unit = value.getDisplayUnit().getQuantity().of(unitString);
50 unitCache.put(key, unit);
51 }
52 return String.valueOf(value.getInUnit((U) unit));
53 }
54
55
56
57
58
59
60 @SuppressWarnings("unchecked")
61 @Override
62 public S deserialize(final Class<S> type, final String text, final String unit)
63 {
64 if (text == null || text.isEmpty())
65 {
66 return null;
67 }
68 try
69 {
70 Method valueOfMethod = valueOfMethodCache.get(type.getName());
71 if (valueOfMethod == null)
72 {
73 valueOfMethod = type.getDeclaredMethod("valueOf", String.class);
74 valueOfMethodCache.put(type.getName(), valueOfMethod);
75 }
76 return (S) valueOfMethod.invoke(null, text + unit);
77 }
78 catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
79 | SecurityException exception)
80 {
81 throw new RuntimeException(exception);
82 }
83 }
84
85 }