View Javadoc

1   /*
2    * Copyright 2006, 2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * 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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package net.sf.morph.transform.converters;
17  
18  import java.util.Locale;
19  
20  import net.sf.morph.transform.DecoratedConverter;
21  import net.sf.morph.transform.ExplicitTransformer;
22  import net.sf.morph.transform.transformers.BaseTransformer;
23  import net.sf.morph.util.ClassUtils;
24  
25  /**
26   * Converts primitive objects to their Object wrappers and vice-versa. Cannot
27   * convert a primitive to a primitive or a wrapper to a wrapper (for those
28   * conversions, use the
29   * {@link net.sf.morph.transform.converters.IdentityConverter}.
30   * 
31   * @author Matt Sgarlata
32   * @since Jun 14, 2006
33   */
34  public class PrimitiveWrapperConverter extends BaseTransformer implements
35  		DecoratedConverter, ExplicitTransformer {
36  
37  	private static final Class[] SOURCE_DEST_CLASSES;
38  	static {
39  		Class[] primitiveTypes = ClassUtils.getPrimitiveTypes();
40  		Class[] wrapperTypes = ClassUtils.getWrapperTypes();
41  		SOURCE_DEST_CLASSES = new Class[primitiveTypes.length + wrapperTypes.length];
42  		System.arraycopy(primitiveTypes, 0, SOURCE_DEST_CLASSES, 0, primitiveTypes.length);
43  		System.arraycopy(wrapperTypes, 0, SOURCE_DEST_CLASSES, primitiveTypes.length, wrapperTypes.length);
44  	}
45  
46  	/**
47  	 * {@inheritDoc}
48  	 */
49  	protected Class[] getSourceClassesImpl() throws Exception {
50  		return SOURCE_DEST_CLASSES;
51  	}
52  
53  	/**
54  	 * {@inheritDoc}
55  	 */
56  	protected Class[] getDestinationClassesImpl() throws Exception {
57  		return SOURCE_DEST_CLASSES;
58  	}
59  
60  	/**
61  	 * {@inheritDoc}
62  	 */
63  	protected boolean isTransformableImpl(Class destinationType, Class sourceType) throws Exception {
64  		return destinationType != null && sourceType != null
65  				&& (sourceType == ClassUtils.getPrimitiveWrapper(destinationType) ||
66  						destinationType == ClassUtils.getPrimitiveWrapper(sourceType));
67  	}
68  
69  	/**
70  	 * {@inheritDoc}
71  	 */
72  	protected Object convertImpl(Class destinationClass, Object source, Locale locale) throws Exception {
73  		return source;
74  	}
75  
76  	/**
77  	 * {@inheritDoc}
78  	 */
79  	protected boolean isWrappingRuntimeExceptions() {
80  	    return true;
81      }
82  
83  }