Using Lombok library, but how to customize/override the setter method

Viewed 5147

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?

2 Answers

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).

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";
    }
}
Related