0

I have a @Value @AllArgsConstructor class, and I want each instance of it to have an ID(The first object has the ID of 1, the second is 2, etc..). until now, before I used lombok but a constructor, my solution used to be: private static int idsCounter = 0; and then this.id = ++idsCounter; inside the constructor.

so how am I supposed to implement this with Lombok which eliminates the constuctor?

  • 2
    ...bite the bullet and write your own constructor? – iluxa Sep 10 '19 at 22:31
  • what if I have many fields? It'll be annoying to write the constructor myself(and use @Getter).. Are you sure that there's no feature to add some code(like a method) which would be applied to created Object? – Techno Freak Sep 10 '19 at 22:33
  • as per https://stackoverflow.com/questions/41156010/is-there-any-postconstruct-feature-of-lombok and https://github.com/rzwitserloot/lombok/issues/1207, it's not a thing – iluxa Sep 10 '19 at 22:51
  • Annoying? How long do you think it will take? More than 15 minutes? – VGR Sep 11 '19 at 02:21
  • Readability? duh? – Techno Freak Sep 12 '19 at 04:53
  • You can bypass the constructor and write something like : `private int id = IDCounter.incrementAndGet();` – bubbles Sep 15 '19 at 11:15

1 Answers1

0

Add an initialisation block:

@AllArgsConstructor
class MyClass {
    static int idsCounter = 0;
    private int id;
    // other fields
    
    {
        id = ++idsCounter;
    }
}

This block runs after the constructor.

It's not a perfect solution because you'll have to provide a value for id, but just provide 0 as it will be overridden by the code in the block.

Bohemian
  • 412,405
  • 93
  • 575
  • 722