View Javadoc

1   /*
2    * Copyright 2004-2008 the Seasar Foundation and the Others.
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.converter.impl;
17  
18  import org.seasar.cubby.converter.ConversionHelper;
19  
20  /**
21   * 任意のオブジェクトから{@link Character}への変換を行うコンバータです。
22   * <p>
23   * 変換元のオブジェクトの文字列表現の先頭の文字を表す{@link Character}へ変換します。 そうでない場合は
24   * <code>null</code> とします。
25   * </p>
26   * 
27   * @author baba
28   * @since 1.1.0
29   */
30  public class CharacterConverter extends AbstractConverter {
31  
32  	/**
33  	 * {@inheritDoc}
34  	 */
35  	public Class<?> getObjectType() {
36  		return Character.class;
37  	}
38  
39  	/**
40  	 * {@inheritDoc}
41  	 */
42  	public Object convertToObject(final Object value, final Class<?> objectType, ConversionHelper helper) {
43  		if (value == null) {
44  			return null;
45  		}
46  		return toCharacter(value.toString());
47  	}
48  
49  	/**
50  	 * 文字列を{@link Character}に変換します。
51  	 * 
52  	 * @param value
53  	 *            文字列
54  	 * @return 文字列を変換した{@link Character}
55  	 */
56  	protected Object toCharacter(final String value) {
57  		if (value == null || value.length() == 0) {
58  			return 0;
59  		}
60  		return value.charAt(0);
61  	}
62  
63  	/**
64  	 * {@inheritDoc}
65  	 */
66  	public String convertToString(final Object value, ConversionHelper helper) {
67  		if (value == null) {
68  			return null;
69  		}
70  		return new String(new char[] { (Character) value });
71  	}
72  
73  }