Java 如何覆盖 Lombok Setter 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51388545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:07:06  来源:igfitidea点击:

How to override Lombok Setter methods

javalombok

提问by Deadpool

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

我使用的龙目岛在我的项目和产生SettersGetters使用@Setters,并@Getters注解POJO类的顶部。我正在尝试覆盖属性的 setter 方法,但它不起作用

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

我想检查 JSON 属性是 Empty 还是 Null 我想在 Setter 方法中设置默认值

@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

我也在这里将其作为参考,但到目前为止还没有运气

采纳答案by maaartinus

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 @Setterstops the generation, too.

在字段级别上确实会阻止生成 setter。但是鉴于您正在定义一个 setter,您甚至不需要它。显式也@Setter停止生成。

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.

我刚刚使用 Eclipse 4.7.3a 和 Lombok 1.18.0 尝试了你的例子,你的(有问题的)setter 被调用了。几年来我一直在使用 Lombok,从未遇到过这样的错误。

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

最有可能的问题是您的 JSON 反序列化器根本不使用 setter。我猜,你正在测试类似的东西

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

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

而不是直接测试setter。这就是问题所在。