ror roro
ror roro

Reputation: 317

java error : constructor is already defined in class - using lombok

The error

java: constructor Restaurant() is already defined in class  
com.example.order_system.domain.Restaurant

appear when I add this class and run the program

@Entity
@NoArgsConstructor
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public class Restaurant {

    @Id
    @GeneratedValue
    private long id;

    @NotEmpty(message = "The restaurant must have a name")
    private String name;

    @NotEmpty(message = "Please add a description for this restaurant")
    private String description;

    @NotEmpty(message = "The restaurant must have a location")
    private String location;

    @OneToMany(mappedBy = "restaurant", fetch = FetchType.EAGER)
    private List<ContactDetails> contactDetails = new ArrayList<>();

}

Upvotes: 10

Views: 24670

Answers (4)

Mu Mind
Mu Mind

Reputation: 11194

Another scenario that causes this error (even with newer Lombok versions) is when running tests in IntelliJ while using its "Annotation processors", which seems to have its own logic that doesn't handle duplicates quite so nicely.

You can fix it with the same workaround of removing one of the conflicting @NoArgsConstructor or @AllArgsConstructor annotations.

Upvotes: 0

Abdullah Khilji
Abdullah Khilji

Reputation: 483

In my scenario, an empty class was present throwing the same above error, removing all the constructor based annotations i.e. @AllArgsConstructor and @NoArgsConstructor, solved the issue for me.

Upvotes: 1

Dmitrii B
Dmitrii B

Reputation: 2860

Try to change @RequiredArgsConstructor to @AllArgsConstructor and that's been fine. See more in documentation

Upvotes: 5

rkosegi
rkosegi

Reputation: 14658

As mentioned in documentation @RequiredArgsConstructor is built using final fields:

@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared. For those fields marked with @NonNull, an explicit null check is also generated. The constructor will throw a NullPointerException if any of the parameters intended for the fields marked with @NonNull contain null. The order of the parameters match the order in which the fields appear in your class.

So either remove @RequiredArgsConstructor annotation or mark some of fields with final keyword (or @NonNull annotation).

Upvotes: 19

Related Questions