1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jadira.bindings.core.general.binding;
17
18 import java.lang.reflect.Constructor;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Modifier;
22
23 import org.jadira.bindings.core.api.Binding;
24 import org.jadira.bindings.core.api.BindingException;
25 import org.jadira.bindings.core.general.marshaller.MethodToMarshaller;
26
27
28
29
30
31
32 public final class MethodConstructorBinding<S, T> extends MethodToMarshaller<S, T> implements Binding<S, T> {
33
34 private final Constructor<S> unmarshal;
35
36
37
38
39
40
41
42 public MethodConstructorBinding(Constructor<S> unmarshal, Class<T> targetClass, Method marshal) {
43
44 super(unmarshal.getDeclaringClass(), targetClass, marshal);
45
46 if (getBoundClass().isInterface()
47 || Modifier.isAbstract(getBoundClass().getModifiers())
48 || getBoundClass().isLocalClass()
49 || getBoundClass().isMemberClass()) {
50 throw new IllegalStateException("unmarshal constructor must have an instantiable target class");
51 }
52
53 this.unmarshal = unmarshal;
54 }
55
56
57
58
59 @Override
60 public S unmarshal(T str) {
61 try {
62 return unmarshal.newInstance(str);
63 } catch (IllegalAccessException ex) {
64 throw new IllegalStateException("Constructor is not accessible");
65 } catch (InstantiationException ex) {
66 throw new IllegalStateException("Constructor is not valid");
67 } catch (InvocationTargetException ex) {
68 if (ex.getCause() instanceof RuntimeException) {
69 throw (RuntimeException) ex.getCause();
70 }
71 throw new BindingException(ex.getMessage(), ex.getCause());
72 }
73 }
74 }