'Java object BigDecimal reflection to setCellValue to double?

I have a Person class defined:

String name;
BigDecimal balance;

I am trying to output its info into SXSSFWorkbook and so far I have the following:

int rowIndex = 0;

List<Person> persons = Arrays.asList(person1, person2, person3)

SXSSFWorkbook wb = new SXSSFWorkbook(100);
CellStyle style = wb.createCellStyle;
style.setDataFormat(workbook.createDataFormat().getFormat("0.00"));

//create sheet etc..
.
.

Field[] fields = Person.class.getDeclaredFields();
for (Person person: persons) {
   Row row = sheetCreateRow(rowIndex++) 
   for (int i = 0; i < fields.length; i++) {
       Cell cell = row.createCell(i);
                
       Field field = dataFields[i];
       field.setAccessible(true);
    
       Object fieldData = fields[i].get(rowData);

       // here is the trouble i am having, since setCellValue does not set for BigDecimal, 
       // I want it to set it as a double by using BigDecimal.doubleValue().
    
       cell.setCellValue(((Double)(fieldData)).doubleValue());

   }
}

fieldDatais a BigDecimal type showing as i.e 100.00 and field is a Field type showing as private java.math.BigDecimal test.project.model.Person.balance.

If I run the method it is throwing an error saying how BigDecimal cannot be casted into a double. And so I am wondering if there is a way to actually grab that BigDecimal value and then use the BigDecimal function doubleValue() so we can set the cell value as a double?



Solution 1:[1]

I agree with tgdavies, your code seems overly complex and there's likely a simpler way to do this. Maybe posting some additional code would help?

But if you just need to cast, you cast the Object to a BigDecimal (because that's what it actually is), and then you call doubleValue().

   Object fieldData = fields[i].get(rowData);

   // here is the trouble i am having, since setCellValue does not set for BigDecimal, 
   // I want it to set it as a double by using BigDecimal.doubleValue().

   BigDecimal bd = (BigDecimal) fieldData;
   double value = bd.doubleValue();

   cell.setCellValue(value);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 markspace