blob: 33bde8f7ab5674d71728ad57159099e8b3914e9d [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.json;
2
3import java.io.*;
4import java.lang.reflect.*;
5import java.text.*;
6import java.util.*;
7import java.util.regex.*;
8
9public class SpecialHandler extends Handler {
10 @SuppressWarnings("rawtypes")
11 final Class type;
12 final Method valueOf;
13 final Constructor< ? > constructor;
14 final static SimpleDateFormat sdf = new SimpleDateFormat();
15
16 public SpecialHandler(Class< ? > type, Constructor< ? > constructor,
17 Method valueOf) {
18 this.type = type;
19 this.constructor = constructor;
20 this.valueOf = valueOf;
21 }
22
23 @Override
24 void encode(Encoder app, Object object, Map<Object, Type> visited)
25 throws IOException, Exception {
26 StringHandler.string(app, object.toString());
27 }
28
29 @Override
30 Object decode(String s) throws Exception {
31 if (type == Pattern.class)
32 return Pattern.compile(s);
33
34 if (constructor != null)
35 return constructor.newInstance(s);
36
37 if (valueOf != null)
38 return valueOf.invoke(null, s);
39
40 throw new IllegalArgumentException("Do not know how to convert a "
41 + type + " from a string");
42 }
43
44}