blob: bcd05ef5a2e22ae05a7042a335fd1921af617e15 [file] [log] [blame]
Stuart McCullochf3173222012-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
Stuart McCulloch4482c702012-06-15 13:27:53 +000016 public SpecialHandler(Class< ? > type, Constructor< ? > constructor, Method valueOf) {
Stuart McCullochf3173222012-06-07 21:57:32 +000017 this.type = type;
18 this.constructor = constructor;
19 this.valueOf = valueOf;
20 }
21
22 @Override
Stuart McCulloch4482c702012-06-15 13:27:53 +000023 void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception {
Stuart McCullochf3173222012-06-07 21:57:32 +000024 StringHandler.string(app, object.toString());
25 }
26
27 @Override
28 Object decode(String s) throws Exception {
29 if (type == Pattern.class)
30 return Pattern.compile(s);
31
32 if (constructor != null)
33 return constructor.newInstance(s);
34
35 if (valueOf != null)
36 return valueOf.invoke(null, s);
37
Stuart McCulloch4482c702012-06-15 13:27:53 +000038 throw new IllegalArgumentException("Do not know how to convert a " + type + " from a string");
Stuart McCullochf3173222012-06-07 21:57:32 +000039 }
40
41}