Java Lombok: Omitting one field in @AllArgsConstructor?

JavaSyntaxConstructorFieldLombok

Java Problem Overview


If I specify @AllArgsConstructor using Lombok, it will generate a constructor for setting all the declared (not final, not static) fields. Is it possible to omit some field and this leave generated constructor for all other fields?

Java Solutions


Solution 1 - Java

No that is not possible. There is a feature request to create a @SomeArgsConstructor where you can specify a list of involved fields.

Full disclosure: I am one of the core Project Lombok developers.

Solution 2 - Java

Alternatively, you could use @RequiredArgsConstructor. This adds a constructor for all fields that are either @NonNull or final.

See the documentation

Solution 3 - Java

Just in case it helps, initialized final fields are excluded.

@AllArgsConstructor
class SomeClass {
    final String s;
    final int i;
    final List<String> list = new ArrayList<>(); // excluded in constructor
}

var x = new SomeClass("hello", 1);

It makes sense especially for collections, or other mutable classes.

This solution can be used together with the other solution here, about using @RequiredArgsConstructor:

@RequiredArgsConstructor
class SomeClass2 {
    final String s;
    int i; // excluded because it's not final
    final List<String> list = new ArrayList<>(); // excluded because it's initialized
}

var x = new SomeClass2("hello");

Solution 4 - Java

A good way to go around it in some cases would be to use the @Builder

Solution 5 - Java

This can be done using two annotations from lombok @RequiredArgsConstructor and @NonNull.

Please find the example as follows

package com.ss.model;

import lombok.*;

@Getter
@Setter
@RequiredArgsConstructor
@ToString
public class Employee {

    private int id;
    @NonNull
    private String firstName;
    @NonNull
    private String lastName;
    @NonNull
    private int age;
    @NonNull
    private String address;
}

And then you can create an object as below

Employee employee = new Employee("FirstName", "LastName", 27, "Address");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3656823View Question on Stackoverflow
Solution 1 - JavaRoel SpilkerView Answer on Stackoverflow
Solution 2 - JavadermoritzView Answer on Stackoverflow
Solution 3 - JavaFerran MaylinchView Answer on Stackoverflow
Solution 4 - JavaenkaraView Answer on Stackoverflow
Solution 5 - JavaShubhasish BhuniaView Answer on Stackoverflow