简体   繁体   中英

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() ?

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

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

eg

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

A more general way to prevent false positives detections of missing @Override by Error Prone (or similar tools) is to configure Lombok to annotate its generated code with @lombok.Generated . This can be done - globally - by adding the following entry to Lombok's lombok.config :

lombok.addLombokGeneratedAnnotation = true

Note that this is not a universal solution - the relevant tool needs to respect @lombol.Generated (or better, any @*.Generated ) annotation.

Tools like Jacoco and Error Prone (very recently) already support it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM