如何使用lombok @Builder和@Data初始化ArrayList [英] How to initialize an ArrayList with lombok @Builder and @Data

查看:333
本文介绍了如何使用lombok @Builder和@Data初始化ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用龙目岛项目,我有一个ArrayList.它为空,因为它从未初始化.在我决定使用 lombok 删除大量样板代码之前,我最初在构造函数中对其进行了初始化.

Using lombok for a project, I have an ArrayList. It's null because it's never initialized. I originally initialized this in the constructor before I decided to use lombok to remove the bulk of boilerplate code.

使其工作最简单的例子是什么?

What's the simplest example of getting it to work?

示例:在创建构建器后,调用refresh会引发空指针(注意:我省略了构建器中使用的变量,但是构建器中未提及 parameters ,因此也许我需要用它做点什么.

Example : Calling refresh throws a null pointer after creating a builder (Note: I've omitted variables that are used in the builder, but parameters is not mentioned in the builder so perhaps I need to do something with it).

@Builder
public @Data class RMF_Objective {

   private ArrayList<String> parameters;

   public void refresh(){     
        parameters.clear(); // Clear for now
   }
}

推荐答案

使用Lombok的生成器进行初始化的最简单的方法是:

The simplest initializing it with the Lombok's builder is like this:

    @Builder
    public @Data class RMF_Objective {

        private ArrayList<String> parameters;

        public void refresh() {
            parameters.clear(); // Clear for now
            System.out.println("cleared !");
        }

        public static void main(String[] args) {
            ArrayList<String> list = new ArrayList<>(Arrays.asList("one", "two"));
            RMF_Objective builtObject = new RMF_ObjectiveBuilder()
                    .parameters(list)
                    .build();
            builtObject.refresh();
        }
    }

否则,您也可以使用Lombok的@Singular批注,使其仅使用一个String作为输入参数来生成parameters()方法的单数"版本.像这样:

Otherwise you could also use Lombok's @Singular annotation to make it generate a 'singular' version of the parameters() method taking only one String as input parameter. Like this:

@Builder
public @Data class RMF_ObjectiveSingular {

    @Singular
    private List<String> parameters;

    public void refresh() {
        parameters.clear(); // Clear for now
        System.out.println("cleared !");
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("one", "two"));
        RMF_ObjectiveSingular builtObject = new RMF_ObjectiveSingularBuilder()
                .parameter("one")
                .parameter("two")
                .build();
        builtObject.refresh();
    }
}

但是,如果我是您,我真的会只使用@Value的Lombok批注.如果不需要构建器,则只需要初始化对象和Getter的构造函数,而不必使用Setter会更简单.不可变对象通常更安全.

But if I were you, I would really use only the @Value's Lombok annotation. If you don't need a builder, it's simpler to have only a constructor initializing the object and Getter but no Setters. Immutables objects are often safer.

这篇关于如何使用lombok @Builder和@Data初始化ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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