Is there a way to modify the @Setter
annotation to add some custom logic to all set methods built via lombok.
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.
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-
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 :)
In general, I would not recommend to change the logic of setFoo
. Silently not setting foo
on an arbitrary condition would expose its usage to bugs or at least misunderstandings.
My suggestion is to either use a custom method explicitly named 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.
From the Lombok @Setter
annotation documentation 'small print' :
Any annotations named @NonNull (case insensitive) on the field are interpreted as: This field must not ever hold null. Therefore, these annotations result in an explicit null check in the generated setter.
您可以通过注释lombok的@Setter和@Getter来添加自己的自定义设置器,然后取消注释。否则,您可以使用@ lombok.experimental.Tolerate标记任何方法以将其从lombok中隐藏。
I'm adding this answer since Sumeet's is outdated as of 2019.
You can provide your own getter or setter logic by simply writing your own methods.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.