我们希望实现 Boolean
处理方式类似于 boolean
当名称以“is”前缀开头时,使用 lombok Getters/Setter。有没有办法用 lombok 做到这一点?
我们总是使用“is”前缀作为 Java(以及 SQL 和 JavaScript)中的成员变量作为编码约定。与boolean
类型我们对 getter/setter 的默认 lombok 行为非常满意。现在我们希望为Boolean
实现相同的生成逻辑。也是如此,但 lombok 默认值与 boolean
之间不同和Boolean
.
我尝试了以下方法:
@Data
public class BooleanChallenge {
// @Getter @Setter just work fine for boolean
private boolean isSmallBoolean;
// Boolean are handled different
private Boolean isBigBoolean;
@Accessors(fluent = true)
private Boolean isFluentAccessor;
@Accessors(prefix = "is")
private Boolean isWithPrefix;
@Accessors(prefix = "is", fluent = true)
private Boolean isWithPrefixAndFluent;
private void useThoseGetterzAndSetterz() {
this.isSmallBoolean(); // ✔ "is"-prefix for getter
this.setSmallBoolean(true); // ✔ "set"-prefix for setter
this.getIsBigBoolean(); // ❌ "get is"
this.setIsBigBoolean(true); // ❌ "set is"
this.isFluentAccessor(); // ✔
this.isFluentAccessor(true); // ❌ "is"-prefix instead of "get" prefix
this.getWithPrefix(); // ❌ no "is"-prefix
this.setWithPrefix(true); // ✔
this.withPrefixAndFluent(); // ❌
this.withPrefixAndFluent(true); // ❌
}
}
最佳答案
这里有一些东西。
不要在看来可怕的事情将继续存在。 另外,Lombok 可以识别糟糕的情况并生成正确的 getter 方法 (示例中为boolean
字段前添加前缀。 这是可怕而荒谬的,因为 JavaBean 规范规定,必须命名boolean
字段的 getterisFieldName
,变为isIsBlammy()
。 停止使用可怕的做法作为你的惯例。isBlammy()
)。- boolean 值的 getter 的正确名称(符合 JavaBean 规范)
(注意大写的“B”)字段是
getFieldName
。 这是故意的,不是错误。 Lombok 生成兼容的 getter 方法。 - Java 在基元和非基元之间自动装箱和自动拆箱 (在本例中,介于 boolean 值和 boolean 值之间)。 当您有一个返回 boolean 值的 getter 并分配返回值时 为 boolean 变量, Java 会自动为赋值生成正确的 boolean 值。
唯一需要 Boolean
的时候是当 null
是有效值时(即可能发生)。
如果 FluentAccessor 永远不能为 null,
将其更改为 boolean
自动装箱将解决您的问题。
当 null
是合法的可能值时,
Boolean
是合适的,而 boolean
不是一个选项。
其他内容
既然改变可怕的命名约定不是一个选择, 您必须自己创建 getter。
这是一个例子:
// Disable the Lombok getIsHooty method creation.
@Getter(AccessLevel.NONE)
private Boolean isHooty;
public Boolean isHooty()
{
return isHooty;
}
关于java - 像处理 Getter/Setter 生成的 boolean 值一样处理 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67635841/