龙目岛如何为布尔对象字段定制 getter?


我的一个 POJO 有一个 Boolean 对象字段,允许在数据库中使用 NULLS (一个需求)。有没有可能在类级别上使用@Data 龙目岛注释,然后覆盖布尔字段的 getter?它为 Boolean 字段生成的默认方法是 getXXX 方法。我希望重写为 isXXX () ?

谢谢,
帕迪

84589 次浏览

what is the name of boolean field? according to the lombok doc:

A default getter simply returns the field, and is named getFoo if the field is called foo (or isFoo if the field's type is boolean)

lombok will generate getter with name isXXX for your boolean field

It's a bit verbose, but you can provide your own isXXX, and then use AccessLevel.NONE to tell Lombok not to generate the getXXX:

@Data
public class OneOfPaddysPojos {


// ... other fields ...


@Getter(AccessLevel.NONE)
private Boolean XXX;


public Boolean isXXX() {
return XXX;
}
}

(And hey, at least it's not quite as verbose as if you weren't using Lombok to begin with!)

I think if you switch your field from Boolean X to boolean X than lombok generate a getter isX() method.

I know the question is old but I will leave this for future references.

You have two options to override a Getter/Setter in your class.

One is the answer from First Option response

The other option is to simply define the getter/setter method and lombok will not automatically produce the specified method.

I tested it myself and it seems to work fine:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ProductResponse {


private UUID id;
private String supplierId;
private String sku;
private String name;
private String brand;
private String imgUrl;
private String description;
private BigDecimal price;
private Float quantity;
private String unit;
//@Getter(AccessLevel.NONE) //This means @Data will not produce a getter for this field so have to explicitly define it
private Set<ProductTag> tags;


//Here we override @Data getter with a different getter (return is different type)
public List<UUID> getTags() {
return     tags.stream().map(ProductTag::getId).collect(Collectors.toList());
}
}

Here is also a reference from the development team comments: Lombok's developer comment

In my example I'm using the "override" feature for a Collection type but this can be used for any other type like Boolean in your case.

From Lombok documentation:

You can always manually disable getter/setter generation for any field by using the special AccessLevel.NONE access level. This lets you override the behaviour of a @Getter, @Setter or @Data annotation on a class.