1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jadira.bindings.core.general.marshaller;
17
18 import java.lang.invoke.MethodHandle;
19 import java.lang.invoke.MethodHandles;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Modifier;
22
23 import org.jadira.bindings.core.api.BindingException;
24 import org.jadira.bindings.core.api.ToMarshaller;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 public class MethodToMarshaller<S, T> implements ToMarshaller<S, T> {
50
51 private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
52
53 private final Class<S> boundClass;
54
55 private final Class<T> targetClass;
56
57 private final MethodHandle marshalHandle;
58
59
60
61
62
63
64
65 public MethodToMarshaller(Class<S> boundClass, Class<T> targetClass, Method marshal) {
66
67 if (marshal.getParameterTypes().length == 0 && Modifier.isStatic(marshal.getModifiers())) {
68 throw new IllegalStateException("marshal method must either be instance scope or define a single parameter");
69 } else if (marshal.getParameterTypes().length == 1 && (!Modifier.isStatic(marshal.getModifiers()))) {
70 throw new IllegalStateException("marshal method must either be instance scope or define a single parameter");
71 } else if (marshal.getParameterTypes().length >= 2) {
72 throw new IllegalStateException("marshal method must either be instance scope or define a single parameter");
73 }
74
75 if (!targetClass.isAssignableFrom(marshal.getReturnType())) {
76 throw new IllegalStateException("marshal method must return an instance of target class");
77 }
78 if (!marshal.getDeclaringClass().isAssignableFrom(boundClass) && !Modifier.isStatic(marshal.getModifiers())) {
79 throw new IllegalStateException("marshal method must be defined as part of " + boundClass.getSimpleName());
80 }
81
82 this.boundClass = boundClass;
83 this.targetClass = targetClass;
84
85 try {
86 this.marshalHandle = LOOKUP.unreflect(marshal);
87 } catch (IllegalAccessException e) {
88 throw new IllegalStateException("Method is not accessible" + marshal);
89 }
90
91 }
92
93
94
95
96
97 public T marshal(S object) {
98
99 try {
100 final T result = (T) marshalHandle.invoke(object);
101 return result;
102 } catch (Throwable ex) {
103 if (ex.getCause() instanceof RuntimeException) {
104 throw (RuntimeException) ex.getCause();
105 }
106 throw new BindingException(ex.getMessage(), ex.getCause());
107 }
108 }
109
110
111
112
113
114 public Class<S> getBoundClass() {
115 return boundClass;
116 }
117
118
119
120
121
122 public Class<T> getTargetClass() {
123 return targetClass;
124 }
125 }