mercredi 3 juillet 2019

Why am I getting a "Cannot set int field to hashmap" error while using get with java reflection?

I am trying to export some java objects to an Excel spreadsheet using Apache POI and java reflection. I have implemented a ExcelWriter class that takes a List of objects of type T and store their values to a spreadsheet. It worked with a couple of different types but I'm getting this "cannot set int field to hashmap" error message, which points to a get method, and I have never used a set method in this class.

Here is the code for this class.

class ExcelWriter<T>{

    private List<T> objList;

    private Field[] fields;

    private Class<T> objClass;

    public ExcelWriter(List<T> objList, Class<T> typeParam) {
        this.objList = objList;
        this.objClass = typeParam;
        this.fields = objClass.getDeclaredFields();
    }

    public void writeXlsToOutputStream(OutputStream responseOutputStream) throws Exception {
        //some code
        fields[i].setAccessible(true);
        row.createCell(i).setCellValue(fields[i].get(obj).toString()); // the error msg points to this line
        //some code
    }

}

Below is the data object class I am trying to export:

//I am also using lombok and mybatis in this class, hence the annotations
@Data
@TableName("bad_detail")
class BadDetailDO{
    @TableId
    private int id;
    //more private fields
}

and the error message:

java.lang.IllegalArgumentException: Can not set int field com.csdt.mi.data.ifir.domain.BadDetailDO.id to java.util.HashMap
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at java.base/jdk.internal.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:56)
    at java.base/jdk.internal.reflect.UnsafeIntegerFieldAccessorImpl.get(UnsafeIntegerFieldAccessorImpl.java:36)
    at java.base/java.lang.reflect.Field.get(Field.java:418)
    at com.csdt.mi.quality.utils.ExcelWriter.writeXlsToOutputStream(ExcelWriter.java:64)
    ...

Any ideas on what caused this?





Aucun commentaire:

Enregistrer un commentaire