1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.morph.transform.converters;
17
18 import java.util.Locale;
19
20 import net.sf.morph.Defaults;
21 import net.sf.morph.transform.Converter;
22 import net.sf.morph.transform.DecoratedConverter;
23 import net.sf.morph.transform.ImpreciseTransformer;
24 import net.sf.morph.transform.transformers.BaseTransformer;
25 import net.sf.morph.util.TransformerUtils;
26
27 /**
28 * Converts an object to a textual representation by calling the object's
29 * <code>toString</code> method. Textual representations include
30 * <code>String</code>s, <code>StringBuffer</code>s and
31 * <code>Character</code>s. Conversions to characters will only succeed if
32 * the result of the conversion is a single character in length.
33 *
34 * @author Matt Sgarlata
35 * @since Dec 24, 2004
36 */
37 public class ObjectToTextConverter extends BaseTransformer implements DecoratedConverter, ImpreciseTransformer {
38
39 private Converter textConverter;
40
41 private static final Class[] SOURCE_TYPES = new Class[] {
42 Object.class
43 };
44
45 /**
46 * {@inheritDoc}
47 */
48 protected Object convertImpl(Class destinationClass, Object source,
49 Locale locale) throws Exception {
50 return getTextConverter().convert(destinationClass, source.toString(),
51 locale);
52 }
53
54 /**
55 * {@inheritDoc}
56 */
57 protected boolean isImpreciseTransformationImpl(Class destinationClass, Class sourceClass) {
58 return TransformerUtils.isImpreciseTransformation(getTextConverter(), destinationClass, String.class);
59 }
60
61 /**
62 * {@inheritDoc}
63 */
64 protected boolean isWrappingRuntimeExceptions() {
65 return true;
66 }
67
68 /**
69 * {@inheritDoc}
70 */
71 protected Class[] getSourceClassesImpl() throws Exception {
72 return SOURCE_TYPES;
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 protected Class[] getDestinationClassesImpl() throws Exception {
79 return getTextConverter().getDestinationClasses();
80 }
81
82 /**
83 * Get the text converter used by this ObjectToTextConverter.
84 * @return Converter
85 */
86 public Converter getTextConverter() {
87 if (textConverter == null) {
88 setTextConverter(Defaults.createTextConverter());
89 }
90 return textConverter;
91 }
92
93 /**
94 * Set the text converter used by this ObjectToTextConverter.
95 * @param textConverter
96 */
97 public void setTextConverter(Converter textConverter) {
98 this.textConverter = textConverter;
99 }
100 }