Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lombok: Omitting one field in @AllArgsConstructor?

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.


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

See the documentation


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


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");

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 a constructor as below

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