gpt4 book ai didi

java - Lombok 继承 : how to set default value for field in superclass without redeclaring it?

转载 作者:行者123 更新时间:2023-12-05 04:36:17 28 4
gpt4 key购买 nike

我正在使用 Lombok,我需要一种方法来自动设置子类中父类(super class)字段的值无需重新声明

It is working fine on its own (@SuperBuiler and @Builder.Default) when using the builder, but it is giving troubles with Spring-Data MongoDB.

org.springframework.data.mapping.MappingException: Ambiguous field mapping detected! Both protected test.jackson.polymorphism.domain.enumeration.EvaluationType test.jackson.polymorphism.domain.models.EvaluationModel.type and private test.jackson.polymorphism.domain.enumeration.EvaluationType test.jackson.polymorphism.domain.models.QuantitativeEvaluationModel.type map to the same field name type! Disambiguate using @Field annotation!

at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity$AssertFieldNameUniquenessHandler.assertUniqueness(BasicMongoPersistentEntity.java:368)
at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity$AssertFieldNameUniquenessHandler.doWithPersistentProperty(BasicMongoPersistentEntity.java:354)
at org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity$AssertFieldNameUniquenessHandler.doWithPersistentProperty(BasicMongoPersistentEntity.java:348)

这些是我的类(class):

public enum EvaluationType{
QUALITATIVE, QUANTITATIVE;
}

@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public abstract class EvaluationModel {
protected EvaluationType type;
protected Integer evaluation;
}

@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class QualitativeEvaluationModel extends EvaluationModel {
/**
* How to set the default value for this field
* without redeclaring it?
*/
@Builder.Default
private EvaluationType type = EvaluationType.QUALITATIVE;
}

@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class QuantitativeEvaluationModel extends EvaluationModel {
/**
* How to set the default value for this field
* without redeclaring it?
*/
@Builder.Default
private EvaluationType type = EvaluationType.QUANTITATIVE;

@Builder.Default
private String currencyCode = Currency.getInstance("EUR").getCurrencyCode();

private BigDecimal economicValue;
}

如何使这些子类的 type 字段具有默认值(可能是最终值),但不重新声明该字段?这应该适用于构造函数和构建器。

最佳答案

解决此问题(并非特定于 Lombok)的解决方案是在子类中使用初始化 block ( https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html)。

@Data
@SuperBuilder
public class QualitativeEvaluationModel extends EvaluationModel {
{
super.type = EvaluationType.QUALITATIVE;
}
}

关于java - Lombok 继承 : how to set default value for field in superclass without redeclaring it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70868565/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com