1

I have a class that stores many fields (both primitive types and objects like String or List). All fields are required and need to be set only once, when the object is created.

What is the correct way to instantiate this using Lombok while ensuring these conditions are met:

1) No warnings due to risk of mutable objects being returned by Setters.

2) Do not use a constructor to instantiate all fields, since number of fields can be >10.

3) Be able to inherit and extend this class, where each subclass will only add more fields, and do nothing else.

4) Be serialization friendly (i.e., have an empty public constructor).

class ParentData {
    int id;
    String name;
}

class ChildData extends ParentData {
    long childId;
    long[] friendId;
    String[] friendNames;
}

Currently, even if I set the fields as private final, I get findBugs errors that the [] objects are mutable.

Seega
  • 3,001
  • 2
  • 34
  • 48
sbhatla
  • 1,040
  • 2
  • 22
  • 34
  • I do not agree that this is a duplicate, at least not to the referenced question. This question is more specific and requires more to solve than just using @Builder. Furthermore, the most upvoted answer of the referenced question involves an all-args constructor, which is explicitly unwanted here. – Jan Rieke Sep 27 '18 at 18:12

2 Answers2

0

May be you could take a look on Builder in lombok

raytong
  • 31
  • 4
  • Would you be so kind to take a look at the stackoverflow how-to-answer guide: https://stackoverflow.com/help/how-to-answer – Casper Sep 27 '18 at 12:01
0

If Constraint 3 means that you want to restrict what subclasses are allowed to do (i.e., be sure that they will never be mutable), then that is not satisfiable, because you cannot enforce immutability on subclasses in Java. If it means "it should be possible to add fields", everything is fine.

That said, you should go with @SuperBuilder and @Getter on the classes. Instead of arrays, use collections with @Singular; Lombok's SuperBuilder will use immutable collection classes then. Use @NonNull on required fields. Add a @NoArgsConstructor for subclasses and serialization frameworks.

I think that's the best you can get with Lombok. There may still be warnings from your linter, but at least partially because the generated code is too complex for it.

PS: Use the current Lombok edge version 1.18.3 or wait for release 1.18.4 for @NonNull support in @SuperBuilder.

Jan Rieke
  • 7,027
  • 2
  • 20
  • 30