如何覆盖Lombok Setter方法 [英] How to override Lombok Setter methods

查看:2223
本文介绍了如何覆盖Lombok Setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用lombok,并在POJO类顶部使用@Setters@Getters批注生成了SettersGetters.我正在尝试覆盖属性的setter方法,但是它不起作用

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

我想检查JSON属性是否为空或空,我想在Setter方法中设置默认值

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;
    }
}

}

工作场景:

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

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

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

失败的情况:

    {
"name":"some"
    }

输出:

DefaultModel(name=some, age=null)

而且我也在以下此处,但到目前为止没有运气

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

推荐答案

要么您遇到了我从未见过的错误,要么您正在测试错误.

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

像这样的注释

@Setter(AccessLevel.NONE) private String age;

实际上,在字段级别上的

阻止了setter的生成.但是考虑到您要定义一个setter,您甚至不需要它.显式的@Setter也会停止生成.

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.

我刚刚使用Eclipse 4.7.3a和Lombok 1.18.0尝试了您的示例,然后调用了(沼泽)设置器.几年来我一直在使用Lombok,但从未遇到过此类错误.

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.

最可能的问题是您的JSON解串器根本不使用setter.我猜,您正在测试类似的东西

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.

这篇关于如何覆盖Lombok Setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆