title logo

Defining new type convertors

Depending on the options specified in the configuration file, the BMProcessor may automatically cast the variable it uses. This casting may be enabled on arguments used:

  • in beans' creations,
  • in method calls,
  • in properties initialization, or
  • in fields initialization

The cast is performed by a method which is able, given a certain type of data, to convert it into another type. For example, the code below handle the conversion of a string into several different target classes:

  /**
   * Default convertor for an object of class String
   *
   * @param str    the string to convert
   * @param target the desired class
   *
   * @return a new object of the desired class
   *
   **/
  public Object convert(String str, Class target)
    throws java.lang.ClassCastException,
    java.lang.NumberFormatException {
    if ((str == null) 
        || target.isInstance(str)
        || target.isAssignableFrom(str.getClass()))
      return str;
    if (target == boolean.class) {
      return new Boolean(str);
    }
    if (target == char.class) {
      if (str.length() != 1) {
        throw new java.lang.ClassCastException("incompatible value for data");
      }
      return new Character(str.charAt(0));
    }
    if (target == byte.class) {
      if ("".equals(str)) str = "0";
      return new Byte(str);
    }
    
    ... similar code to convert the string into 'short', 'int', ...
    
    if (target == java.awt.Color.class) {
      Integer c = Integer.decode(str);
      return new java.awt.Color(c.intValue());
    }
    throw new java.lang.ClassCastException("impossible conversion from "
                                           + "an object of class "
                                           + str.getClass().getName()
                                           + " to an object of class "
                                           + target.getName() +".");
  }

The classes where type convertors are defined must be registered in the configuration file in the following way:

<register type="typeConvertor"
          method="convert"
          class="fr.inria.ketuk.TypeConvertor"/>
blank horizontal line
Made with CSS Valid XHTML 1.0! Valid CSS! Copyright © 2000 INRIA, Dyade, Bull
Created by Claude Pasquier