使Lombok Builder实施两个类带有公共字段的界面
假设我有一个接口和 2 个这样的类:
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;
}
所以这些类有 3 个公共字段 cost
、dateOfPurchase
和 customer
,以及接口这两个类的构建者都可以实现。
有没有办法让我在 lombok @Builder
或 @SuperBuilder
注释中指定构建器正在实现某些接口方法?
在有人问“你为什么要这样做?”之前,这是因为我正在使用两个非常相似的模型的代码库,并且将数据附加到这两个类的构建器的逻辑是非常复杂的重复代码。到目前为止,我写出了所有样板构建器代码,以便创建一个使用该接口附加数据的单一方法。但我想使用注释,以便在数据模型发生变化时不必更新样板。
或者...我是否只需要创建一个具有公共字段并使用 @SuperBuilder 注释的抽象父类?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有;自己制作建造者。 Lombok 将自动“填充”:
Lombok 仍会生成其他所有内容,因此您的构建器类的内容可以保持为空。
There is; make the builder yourself. Lombok will 'fill in' automatically:
Lombok will still generate everything else, hence why the contents of your builder class can remain empty.