Open Source Repository

Home /jodd/jodd-3.3.2 | Repository Home



jodd/typeconverter/impl/CharacterConverter.java
// Copyright (c) 2003-2012, Jodd Team (jodd.org). All Rights Reserved.

package jodd.typeconverter.impl;

import jodd.typeconverter.TypeConversionException;
import jodd.typeconverter.TypeConverter;

/**
 * Converts given object to <code>Character</code>.
 * Conversion rules:
 <li><code>null</code> value is returned as <code>null</code>
 <li>object of destination type is simply casted
 <li><code>Number</code> is converted to <code>char</code> value
 <li>finally, <code>toString()</code> value of length 1 is converted to <code>char</code>
 */
public class CharacterConverter implements TypeConverter<Character> {

  public Character convert(Object value) {
    if (value == null) {
      return null;
    }
    if (value.getClass() == Character.class) {
      return (Charactervalue;
    }
    if (value instanceof Number) {
      char c = (char) ((Numbervalue).intValue();
      return Character.valueOf(c);
    }
    try {
      String s = value.toString();
      if (s.length() != 1) {
        throw new TypeConversionException(value);
      }
      return Character.valueOf(s.charAt(0));
    catch (IndexOutOfBoundsException ioobex) {
      throw new TypeConversionException(value, ioobex);
    }
  }

}