Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use 'toString()' as source in org.mapstruct.Mapping?

I want to use Foo::toString as source in @org.mapstruct.Mapping

Solutions below doesn't work:

@Mapping(source = "value.toString()", target = "date")
String map(Foo value);

java: The type of parameter "value" has no property named "toString()".

@Mapping(source = "java(value.toString())", target = "date")
String map(Foo value);

java: No property named "java(value.toString())" exists in source parameter(s).


  • I cannot change Foo class (no Lombok insite)
  • Mapper configuration: @Mapper(componentModel = "spring").
  • Any advice?

Let's define Foo as:

public class Foo {
    private final int x;
    public Foo(int x) {
        this.x = x;
    }
    public String toString() {
        return "" + this.x;
    }
}

using:

    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>1.4.2.Final</version>
    </dependency>

...

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>1.4.2.Final</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
like image 290
THM Avatar asked Oct 25 '25 03:10

THM


2 Answers

MapStruct does not support generating mapping methods for Object to String like that.

What you can do is to write your own custom method.

e.g.

default String map(Foo value) {
    return value != null ? value.toString() : null;
}
like image 70
Filip Avatar answered Oct 26 '25 17:10

Filip


looks like this solution is working:

@Mapping(expression = "java(value.toString())", target = "foo")

but on different level (on parent object which contains field with type Foo ) like:

public class Bar {
    Foo foo;
}
like image 23
THM Avatar answered Oct 26 '25 17:10

THM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!