jeudi 16 juillet 2020

How to set Non primitive type field value using Java Reflection

I am reading longitude & latitude from an Excel file and mapping into a model class. But when I try to set value in a non-primitive Double field getting IllegalArgumentException

Can not set java.lang.Double field org.dataexchanger.osm.example.BankBranch.longitude to java.lang.String

Here is the Model Class code:

@Data
@SheetEntity(value = "BankBranch")
public class BankBranch {
    @Column(name = "Branch Name")
    private String branchName;
    
    @Column(name = "Branch Code")
    private String branchCode;
    
    @Column(name = "Lat")
    private Double longitude;
    
    @Column(name = "Lon")
    private Double latitude;
}

The Parser code:

private void setFieldValue(Object instance, String value) throws IllegalAccessException {
    for(Field field : instance.getClass().getDeclaredFields()){
        try{
            if(field.getType() == Double.class || field.getType() == double.class)
                field.set(instance, Double.valueOf(value)); /** here is the problem */
        }catch (IllegalArgumentException ex){
            ex.printStackTrace();
        }
    }
}

For example: values = 23.8333892 Which is a longitude

Here is the Exception code:

java.lang.IllegalArgumentException: Can not set java.lang.Double field org.dataexchanger.osm.example.BankBranch.latitude to java.lang.String
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
    at java.lang.reflect.Field.set(Field.java:764)
    at org.dataexchanger.osm.SheetImporter.setTypeSpecificValue(SheetImporter.java:101)
    at org.dataexchanger.osm.SheetImporter.setFieldValue(SheetImporter.java:74)
    at org.dataexchanger.osm.SheetImporter.lambda$null$0(SheetImporter.java:52)
    at java.lang.Iterable.forEach(Iterable.java:75)
    at org.dataexchanger.osm.SheetImporter.lambda$null$1(SheetImporter.java:44)
    at java.lang.Iterable.forEach(Iterable.java:75)
    at org.dataexchanger.osm.SheetImporter.lambda$mapSheetToClass$2(SheetImporter.java:36)
    at java.lang.Iterable.forEach(Iterable.java:75)
    at org.dataexchanger.osm.SheetImporter.mapSheetToClass(SheetImporter.java:35)
    at org.dataexchanger.osm.SheetImporter.mapSheetToClass(SheetImporter.java:28)
    at org.dataexchanger.osm.ExcelImportTest.testExcelImport(ExcelImportTest.java:27)




Aucun commentaire:

Enregistrer un commentaire