Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Lombok Setter methods

Tags:

java

lombok

I'm using lombok in my project and generation Setters and Getters using @Setters and @Getters annotations on top of POJO class. I'm trying to override setters method of a property but it's not working

I want to check if JSON property is Empty or Null i want to set default value in Setter method

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ToString
public class DefaultModel {


private String name;
@Setter(AccessLevel.NONE)private String age;    

public void setAge(String age) {
     if(age==null||age.trim().isEmpty()||age.equals("null")) {
        this.age="10";
    }else {
        this.age=age;
    }
}

}

Working scenarios:

        {
"name":"some",
"age":null
     }

     {
"name":"some",
"age":"null"
     }

    {
"name":"some",
"age":"  "
     }

Failed Scenario :

    {
"name":"some"
    }

Output:

DefaultModel(name=some, age=null)

And i'm following this as reference also here, but no luck so far

like image 821
Deadpool Avatar asked Jul 17 '18 19:07

Deadpool


People also ask

Can we override setter in Lombok?

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.

How do you avoid getters and setters in spring boot?

You can use Lombok . It is a small java library that can be used to reduce the amount of boilerplate java code. Lombok does this via annotations that can be added to the java classes. For getters/setters Lombok provides @Getter and @Setter annotations.

How do you use a setter in Lombok?

We will use the @Getter and @Setter annotations on the class level. This will generate the getters and setters method for any non-static fields in the class. Each fields in the class will have its corresponding getter and setter. For example the username field will have the getUsername() and setUsername() method.


Video Answer


1 Answers

Either you just hit a bug I've never seen or you're testing it wrong.

An annotation like

@Setter(AccessLevel.NONE) private String age;

on the field level indeed stops the setter from being generated. But given that you're defining a setter, you don't even need it. An explicit @Setter stops the generation, too.

I've just tried your example using Eclipse 4.7.3a and Lombok 1.18.0 and your (buggy) setter gets called. I've been using Lombok a lot over a few years and never encountered such a bug.

Most probably the problem is that your JSON deserializer does not use setters at all. I guess, you're testing something like

DefaultModel defaultModel = deserialize("{\"name\":\"some\"}", DefaultModel.class);

instead of testing the setter directly. And that's the problem.

like image 93
maaartinus Avatar answered Sep 18 '22 02:09

maaartinus