Home > Back-end >  Adding @NoArgsConstructor anotationg causes error
Adding @NoArgsConstructor anotationg causes error

Time:09-28

I have a Student class that needs a default constructor, I want to add it with the @NoArgsConstructor annotation the problem is that when I add it all my variables give an error "Variable 'xxx' might not have been initialized"

This is the class

import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.*;

import java.util.UUID;
@Getter
@NoArgsConstructor

@Entity
public class Student {


    private final UUID studentId;
    private final String firstName;
    private final String lastName;
    private final String email;
    private final Gender gender;




    public Student(
              @JsonProperty("studentId") UUID studentId
            , @JsonProperty("firstName")String firstName
            , @JsonProperty("lastName")String lastName
            , @JsonProperty("email")String email
            ,@JsonProperty("gender") Gender gender) {
        this.studentId = studentId;
        this.firstName = firstName;
        this.lastName = lastName;

        this.email = email;
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student{"  
                "studentId="   studentId  
                ", firstName='"   firstName   '\''  
                ", lastName='"   lastName   '\''  
                ", email='"   email   '\''  
                ", gender="   gender  
                '}';
    }

    enum Gender{
        MALE,FEMALE,male,female
    }
}

CodePudding user response:

All the fields in your class are final and are expected to be initialised when an instance of object is created and not changed. When you use @NoArgsConstructor you are creating a constructor that can be used to create the object without initialising the values. If you want an object to be created without values you can remove the final keyword as follows:

    private UUID studentId;
    private String firstName;
    private String lastName;
    private String email;
    private Gender gender;

If you want the values to be assigned during object creation remove @NoArgsConstructor.

  • Related