我正在使用 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/
相关文章:
python - Kubernetespodoperator如何使用cmds或者cmds和argum
visual-studio - 如何在 D 盘中完全安装 Visual Studio?
c++ - 用方括号 [] 初始化 std::vector
snowflake-cloud-data-platform - 如何设置开发人员以在雪花(和 dbt
exception - 如何跳过在 Kafka 中产生运行时异常的记录并保持流运行?
javascript - 在 React.js 中使用 Dropzone 时如何将图像上传到 Fir