Stuart McCulloch | f317322 | 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 | |
Stuart McCulloch | 4482c70 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 16 | public SpecialHandler(Class< ? > type, Constructor< ? > constructor, Method valueOf) { |
Stuart McCulloch | f317322 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 17 | this.type = type; |
| 18 | this.constructor = constructor; |
| 19 | this.valueOf = valueOf; |
| 20 | } |
| 21 | |
| 22 | @Override |
Stuart McCulloch | 4482c70 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 23 | void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception { |
Stuart McCulloch | f317322 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 24 | 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 McCulloch | 4482c70 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 38 | throw new IllegalArgumentException("Do not know how to convert a " + type + " from a string"); |
Stuart McCulloch | f317322 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | } |