Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.lib.json; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.lang.reflect.*; |
| 5 | import java.text.*; |
| 6 | import java.util.*; |
| 7 | import java.util.regex.*; |
| 8 | |
| 9 | public 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 | } |