[英]Custom setter via Lombok
Is there a way to modify the @Setter
annotation to add some custom logic to all set methods built via lombok. 有没有一种方法可以修改@Setter
注释,以便为通过@Setter
构建的所有set方法添加一些自定义逻辑。
I have a class with the fields initialized with some default values. 我有一类用一些默认值初始化的字段。 Now I only want to set the value in the fields if the value is not null. 现在,我只想在值不为null的情况下在字段中设置值。
Example, something that generates- 例如,产生的东西-
public void setFoo(int foo) {
if (foo != null) {
this.foo = foo;
}
}
For example, if I am using the @Setter
annotation on a Jersey Update Request class, instead of doing things like- 例如,如果我在Jersey更新请求类上使用@Setter
注释,而不是执行以下操作:
if (request.getFoo() != null) {
this.foo = request.getFoo();
}
I should be able to directly do- 我应该能够直接做到-
this.setFoo(request.getFoo());
with some results. 有一些结果。
I assume you meant to use Integer
instead of int
, which does not allow null values and therefore solves your problem :) 我假设您打算使用Integer
而不是int
,后者不允许空值,因此可以解决您的问题:)
In general, I would not recommend to change the logic of setFoo
. 通常,我不建议更改setFoo
的逻辑。 Silently not setting foo
on an arbitrary condition would expose its usage to bugs or at least misunderstandings. 默默地不将foo
设置在任意条件下会将其用法暴露给bug或至少引起误解。
My suggestion is to either use a custom method explicitly named setFooIfNotNull(Integer foo)
. 我的建议是使用显式命名为setFooIfNotNull(Integer foo)
的自定义方法。 A possible alternative solution would be to mark the field foo
with the annotation @NonNull
to throw a NullPointerException in a case of null values. 一种可能的替代解决方案是在字段foo
上标注@NonNull
注释,以在出现空值的情况下引发NullPointerException。
From the Lombok @Setter
annotation documentation 'small print' : 从Lombok @Setter
注释文档“小字体”中 :
Any annotations named @NonNull (case insensitive) on the field are interpreted as: This field must not ever hold null. 字段上任何名为@NonNull(不区分大小写)的注释都将解释为:此字段永远不能为null。 Therefore, these annotations result in an explicit null check in the generated setter. 因此,这些注释会在生成的setter中导致显式的null检查。
您可以通过注释lombok的@Setter和@Getter来添加自己的自定义设置器,然后取消注释。否则,您可以使用@ lombok.experimental.Tolerate标记任何方法以将其从lombok中隐藏。
I'm adding this answer since Sumeet's is outdated as of 2019. 我要添加此答案,因为Sumeet的日期截至2019年已过时。
You can provide your own getter or setter logic by simply writing your own methods. 您可以通过简单地编写自己的方法来提供自己的getter或setter逻辑。
package com.example;
import lombok.Getter;
@Getter
public class Foo {
//Will not generate a getter for 'test'
private String test;
//Will generate a getter for 'num' because we haven't provided our own
private int num;
public String getTest(){
if(test == null){
throw new Exception("Don't mind me, I'm just a silly exception");
}
return test;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.