What is the difference between getRichStringCellValue().getString() and getRichStringCellValue().toString()

StackOverflow https://stackoverflow.com/questions/22452190

  •  15-06-2023
  •  | 
  •  

Pregunta

I am currently using Apache POI for handling MS Excel files, and I came across something that seemed weird to me. The HSSFCell class has a method called getRichStringCellValue() that returns a HSSFRichTextString object. In order to convert this to a normal string, we use getString(). Looks like this:

cell.getRichStringCellValue().getString()

Now what got me wondering is, why is there a getString() in the first place, when toString() does essentially the same thing, i.e. returns the string equivalent? Does anyone know why?

¿Fue útil?

Solución

The contract of toString():

toString method returns a string that "textually represents" this object

The general purpose of toString() is to provide a human-readable representation of the object. Some classes go further and specify the detailed format of toString(), which is not generally advisable, and if so, then only for the "value objects" (date, time, number).

Unless specified in the class's javadoc, you should never rely on a specific format of the text returned by toString().

The general recommendation: if your class wants to introduce a specific persistent text representation, it should be provided by a separate method. Thus you are never unpleasantly surprised if the implementation of toString() changes later.

Otros consejos

The underlying implementation is the same for both methods:

return _string.toString();

My guess is they added the getter to be able to use it as a bean property.

BTW: you might want to check for nulls before doing cell.getRichStringCellValue().getString()

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top