Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell to lombok the generated getter is an @Override

I'm using lombok in my project and I have an interface :

public interface MyInterface{

    Object getA()
}

And a class

@Getter
public class MyClass implements MyInterface{

      private Object a;

      private Object b

}

And i've checked the generated class and the method generated in the class is not @Override

I'm wondering how to add this annotation ? And what are the consequences of a missing @Override ?

It's maybe an another question but this code is analyzed by sonarqube and sonar say that private field a is never used.

I've already seen the subject about sonarqube + lombok = false positives

But In my case b doesn't create a false positive. So I don't think this is directly related

Do you see a solution to avoid this problems without reimplement getA() ?

like image 869
Ruokki Avatar asked Sep 19 '25 14:09

Ruokki


2 Answers

You can use the onMethod attribute of the annotation to add any annotation you want to the generated method.

@Getter
public class MyClass implements MyInterface{
    @Getter(onMethod = @__(@Override))
    private Object a;
    private Object b
}

As a matter of style in this case, I would probably move the class-level @Getter to the other field. If there were c, d, e which should all use normal (no annotation) @Getter logic, I would leave it as above.

public class MyClass implements MyInterface{
    @Getter(onMethod = @__(@Override))
    private Object a;
    @Getter
    private Object b
}

You may also want to enable Lombok's generated annotations. It will prevent some tools (coverage, static analysis, etc) from bothering to check Lombok's methods. Not sure if it will help in this case, but I pretty much have it enabled in all of my projects.

lombok.addLombokGeneratedAnnotation = true
like image 183
Michael Avatar answered Sep 21 '25 06:09

Michael


You can add @Override to a particular field by using @Getter's onMethod.

e.g.

@Getter(onMethod = @__(@Override))
private Object a;

@Override has no affect on the code itself. It simply informs the compiler that the method is overriding a method from its superclass. The compiler will fail the build if the method does not override a method from a superclass.

like image 25
Christopher Schneider Avatar answered Sep 21 '25 04:09

Christopher Schneider