Search code examples
javaeclipsemappingnumber-formattingmapstruct

Mapping of "dirty" string fields to double using MapStruct in an Eclipse project


Given:

I am using MapStruct in my Eclipse project to convert a "dirty" string into a number:

String SourcePojo.area = "120,5 sqm"
double TargetPojo.area = 120.5

I can convert the "dirty" string into the number by:

double extractDoubleFromString(String string) throws ParseException{
    NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
    return format.parse(string).doubleValue();
}

What I've tried

Using Mapstruct I wrote this Mapper:

@Mapper
public interface MyMapper {

    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);
    
    
    @Mapping(source="space", target="space", qualifiedByName="StringToDouble")
    TargetPojo mapSourceToTarget(TargetPojo aAED);
    
    @Named("StringToDouble")
    default double extractDoubleFromString(String string) throws ParseException{
        NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
        return format.parse(string).doubleValue();
    }
}

In the generated MapperImpl I found this code:

if ( aAED.getSpace() != null ) {
    targetPojo.space( Double.parseDouble( aAED.getSpace() ) );
}

It looks like the named method is not used at all. I still get the same error as before I added it.


Solution

  • The code is perfectly ok and should work. The reason it did not was, that MapStruct is not invoked by the normal Eclipse Builder but through the Maven build process. (At least this is true for my setup)

    After a complete maven clean install, the new mapper was created and everything worked well.