Search code examples
xstream

NumberFormatException xstream


I have a very strange behavior from xstream. My test code is:

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class ConvertStringToNumber{

  public static void  main(String[] args) {

    XStream xstream = new XStream(new DomDriver());
    xstream.alias("person", Person.class);

    Person c = (Person) xstream.fromXML("<person><code>01008</code></person>");
    System.out.println(c);
  }
}

class Person {
  private int code;
  public void setCode(int code){
  this.code=code;
  }
  public int getCode(){
  return this.code;
  }
}

When I run this code with String : <person><lastname>001008</lastname></person> as the XML input I got a NumberFormatException and also with <person><lastname>001009</lastname></person>

Other numbers work just fine, e.g.: 001000, 001007, 001006, 001005.

Do you have any idea what might be the problem?


Solution

  • When you left pad a number with a single zero java considers the number a octal number.

    Octal numbers can only have the following digits: 0,1,2,3,4,5,6 & 7. The numbers 8 and 9 cannot be used in octal numbers.

    The number you have specified is 01008, hence it throws NumberFormatException.