1 /*
2 * Copyright 2011 Chris Pheby
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.jadira.bindings.core.general.marshaller;
17
18 import org.jadira.bindings.core.api.Converter;
19 import org.jadira.bindings.core.api.ToMarshaller;
20
21 /**
22 * Base class providing capability to perform marshalling of source object type
23 * to target. This class uses reflection.
24 * <p>
25 * The marshal method must either
26 * </p>
27 * <p>
28 * a) be instance scoped and defined as part of class S. It must accept no
29 * parameters and return a type of T. For example:
30 * </p>
31 * <p>
32 * {@code public String marshal()}
33 * </p>
34 * <p>
35 * b) be statically scoped. It must accept a single parameter of type S and
36 * return a type of T. For example:
37 * </p>
38 * <p>
39 * {@code public static String marshal(BoundType param)}
40 * </p>
41 * @param <S> Source type for the conversion
42 * @param <T> Source type
43 */
44 public class ConverterToMarshaller<S, T> implements ToMarshaller<S, T> {
45
46 private final Converter<S,T> converter;
47
48 /**
49 * Create a new instance for the given converter
50 * @param converter The converter to be wrapped
51 */
52 public ConverterToMarshaller(Converter<S,T> converter) {
53
54 if (converter == null) {
55 throw new IllegalStateException("converter must not be null");
56 }
57 this.converter = converter;
58 }
59
60 /**
61 * {@inheritDoc}
62 */
63 /* @Override */
64 public T marshal(S object) {
65
66 return converter.convert(object);
67 }
68
69 /**
70 * {@inheritDoc}
71 */
72 /* @Override */
73 public Class<S> getBoundClass() {
74 return converter.getInputClass();
75 }
76
77 /**
78 * {@inheritDoc}
79 */
80 /* @Override */
81 public Class<T> getTargetClass() {
82 return converter.getOutputClass();
83 }
84 }