2

I use lombok library in my java project.

@Data
public class Score {
   private long grade;
}

With this code, I have getter and setter automatically. e.g.

Score score = new Score();
score.setGrade(10);
// when I call score.getGrade(), I get 10.

But now I want to customize the setter method to introduce additional logics for the grade value. e.g.

public void setGrade(long grade) {
       // so the returned value from getter is always 1 bigger than what has been set.
       this.grade += 1; 
   }

Basically, I want to have score.setGrade(10) but score.getGrade() returns 11. That's override the setter. How to achieve it with lombok in use?

Leem
  • 15,772
  • 32
  • 101
  • 149
  • You can just define this method in the class, Lombok will use that then. – daniu Feb 27 '20 at 14:12
  • No need to have `@override` annotation? Could you please post an example? – Leem Feb 27 '20 at 14:14
  • You've got a good answer, the linked question has some additional related info. Concerning customization: You can't modify what Lombok setter does (e.g., notify observers or alike). All you can do is to stop Lombok from generating the setter and write your own. – maaartinus Feb 27 '20 at 22:42

2 Answers2

4

You can just write the getter method in the class. Lombok will not override methods. If a method that it should generate is already present, it will skip that one.

So you could do this:

@Data
public class Score {
  private long grade;

  public void setGrade(long grade) {
    this.grade = grade + 1;
  }
}

Or instead just override the getter:

@Data
public class Score {
  private long grade;

  public long getGrade() {
    return this.grade + 1;
  }
}

Edit: To add on your comment: @Override is only required if you override methods from superclasses or interfaces. Lombok injects the method directly into your class, thus no @Override is required (and it will cause an compiler error, because there is nothing that could be overridden).

marandus
  • 1,138
  • 1
  • 10
  • 20
  • What if I want to pass additional external parameter to the method, is that fine? – Leem Feb 27 '20 at 14:20
  • @Leem that will result in the automatically generated setter with only one argument along the one with the one you declared. – daniu Feb 27 '20 at 14:27
0

This works fine for me

class Scratch {
    public static void main(String[] args) {
        MyDataClass object = new MyDataClass();
        object.setOverriddenSet("some value");
        if (!"fixed value".equals(object.getOverriddenSet())) {
            throw new RuntimeException();
        }
        System.out.println("all went well.");
    }
}

@Data
class MyDataClass {
    String generated;
    String overriddenSet = "fixed initial value";

    void setOverriddenSet(String setTo) {
        overriddenSet = "fixed value";
    }
}
daniu
  • 13,079
  • 3
  • 28
  • 48