mkarneim / pojobuilder

A Java Code Generator for Pojo Builders
Other
334 stars 44 forks source link

Generated copy() method does not copy all fields #176

Open jza70 opened 2 years ago

jza70 commented 2 years ago

PojoBuilder generates copy() method with annotation @GeneratePojoBuilder(withCopyMethod = true). It may skip generation of this method if all pojo properties are final, but should work for all non-final properties. Right? Wrong.

If your class defines custom accessor methods with Optionals, like this one:

@GeneratePojoBuilder(withCopyMethod = true)
public class Flight {
    private String flightNumber;

    private Integer journeyMins;

    private Integer numStops;

    void setFlightNumber(String flightNumber) {
        this.flightNumber = flightNumber;
    }

    void setJourneyMins(int journeyMins) {
        this.journeyMins = journeyMins;
    }

    void setNumStops(int numStops) {
        this.numStops = numStops;
    }

    public String getFlightNumber() {
        return flightNumber;
    }

    public Optional<Integer> getJourneyMinsOptional() {
        return Optional.ofNullable(journeyMins);
    }

    public Integer getJourneyMins() {
        return journeyMins;
    }

    public Optional<Integer> getNumStopsOptional() {
        return Optional.ofNullable(numStops);
    }
}

PojoBuilder will generate this copy method:

 /**
     * Copies the values from the given pojo into this builder.
     *
     * @param pojo
     * @return this builder
     */
    public FlightBuilder copy(Flight pojo) {
        withFlightNumber(pojo.getFlightNumber());
        return self;
    }

Two properties are missing even though "with" methods are generated properly.

Please fix it.