javalombokintellij-lombok-plugin

Make lombok builder implement interface for 2 classes with common fields


Let's say I have an interface and 2 classes like this:

public interface FinancialTransactionBuilder {
    FinancialTransactionBuilder cost(int cost);
    FinancialTransactionBuilder dateOfPurchase(Date date);
    FinancialTransactionBuilder customer(Customer customer);
}
@Builder 
public class ProductPurchaseInstance{
    int cost;
    Date dateOfPurchase;
    Customer customer;
    String productSerialNumber;
}
@Builder 
public class ServicePurchaseInstance {
    int cost;
    Date dateOfPurchase;
    Customer customer;
    Service serviceSold;
}

So the classes have 3 common fields cost, dateOfPurchase, and customer, and the interface is something that the builders for both of those classes can implement.

Is there a way for me to specify in the lombok @Builder or @SuperBuilder annotations that the builder is implementing some interface methods?

Before someone asks "Why would you do this?", it's because I'm working in a codebase with 2 very similar models, and the logic to append data to the builders for those 2 classes was very complex duplicated code. As of now, I wrote out all the boiler plate builder code in order to make a single method that uses the interface for appending data. But I'd like to use the annotations so that the boiler plate doesn't have to be updated whenever the data model changes.

Or...do I just have to go and make an abstract parent class that goes and has the common fields and use the @SuperBuilder annotation?


Solution

  • There is; make the builder yourself. Lombok will 'fill in' automatically:

    @Builder
    public class ServicePurchase {
        int cost;
        Date dateOfPurchase;
        Customer customer;
        Service serviceSold;
    
        public static class ServicePurchaseBuilder implements FinancialTransactionBuilder {}
    }
    

    Lombok will still generate everything else, hence why the contents of your builder class can remain empty.